avfoundation开始使用avfoundation


备注

本节概述了avfoundation是什么,以及开发人员可能想要使用它的原因。

它还应该提到基础中的任何大型主题,并链接到相关主题。由于avfoundation的文档是新的,您可能需要创建这些相关主题的初始版本。

安装或设置

相机输出预览的最小设置(Swift 2,Swift 3)

import UIKit
import AVFoundation

class ViewController: UIViewController {
    var session: AVCaptureSession?
    var cameraPreviewLayer: AVCaptureVideoPreviewLayer?

    override func viewDidLoad() {
        super.viewDidLoad()
        setupSession()
        if let cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: session) {
            view.layer.addSublayer(cameraPreviewLayer)
            self.cameraPreviewLayer = cameraPreviewLayer
            session?.startRunning()
        }
    }

    func setupSession() {
        session = AVCaptureSession()
        //setup input
        let device =  AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
        do {
            let input = try AVCaptureDeviceInput(device: device)
            if session?.canAddInput(input) == true {
                session?.addInput(input)
            }
        } catch {
            print("An error occured: \(error.localizedDescription)")
        }


        //setup output
        let output = AVCaptureVideoDataOutput()
        output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable: kCVPixelFormatType_32BGRA]
        if session?.canAddOutput(output) == true {
            session?.addOutput(output)
        }
    
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.cameraPreviewLayer?.frame = self.view.layer.bounds
    }
}