欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Setting Up a Capture Session(swift之AVCaptureSession AVCaptureDevice AVFoundation)

程序员文章站 2022-04-08 23:18:57
...

返回上级目录:ios AVFoundation(音视频解码,直播,相机)

官方文档

苹果官方文档:Setting Up a Capture Session

示例代码:

import UIKit
import AVFoundation

class PreviewView: UIView {
    override class var layerClass: AnyClass {
        return AVCaptureVideoPreviewLayer.self
    }
    
    var videoPreviewLayer: AVCaptureVideoPreviewLayer {
        return layer as! AVCaptureVideoPreviewLayer
    }
    
}

class ViewController: UIViewController {
    
    var captureSession: AVCaptureSession?
    
    let previewView = PreviewView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        switch AVCaptureDevice.authorizationStatus(for: .video) {
            case .authorized: // The user has previously granted access to the camera.
                self.setupCaptureSession()

            case .notDetermined: // The user has not yet been asked for camera access.
                AVCaptureDevice.requestAccess(for: .video) { granted in
                    if granted {
                        self.setupCaptureSession()
                    }
                }

            case .denied: // The user has previously denied access.
                return

            case .restricted: // The user can't grant access due to restrictions.
                return
        }
        
    }
    
    func setupCaptureSession() {
        captureSession = AVCaptureSession()
        guard let captureSession = captureSession else {
            return
        }
        captureSession.beginConfiguration()
        let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)
        guard let videoDeviceInput = try? AVCaptureDeviceInput(device: videoDevice!),captureSession.canAddInput(videoDeviceInput) else {
            return
        }
        captureSession.addInput(videoDeviceInput)
        
        let photoOutput = AVCapturePhotoOutput()
        guard captureSession.canAddOutput(photoOutput) else { return }
        captureSession.sessionPreset = .photo
        captureSession.addOutput(photoOutput)
        captureSession.commitConfiguration()
        
        previewView.frame = view.bounds
        previewView.videoPreviewLayer.session = captureSession
        view.addSubview(previewView)
        
        captureSession.startRunning()
    }

}

AVCaptureDevice.default方法三个参数的解释

参数的枚举选择不对,可能会导致初始化失败。如设备类型你选了.builtInDualWideCamera.但是6s的手机没有两个广角相机,那么在6s手机上运行是就会返回nil

Setting Up a Capture Session(swift之AVCaptureSession AVCaptureDevice AVFoundation)

设备类型 AVCaptureDevice.DeviceType
Setting Up a Capture Session(swift之AVCaptureSession AVCaptureDevice AVFoundation)

Setting Up a Capture Session(swift之AVCaptureSession AVCaptureDevice AVFoundation)
参考:
OC之AVCaptureDevice

相关标签: ios 面试