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

返回上级目录: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

在这里插入图片描述

设备类型 AVCaptureDevice.DeviceType
在这里插入图片描述

在这里插入图片描述
参考:
OC之AVCaptureDevice

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页