How to get front camera, back camera and audio with AVCaptureDeviceDiscoverySession

后端 未结 11 1416
闹比i
闹比i 2020-12-12 20:58

Before iOS 10 came out I was using the following code to get the video and audio capture for my video recorder:

 for device in AVCaptureDevice.devices()
 {
          


        
11条回答
  •  没有蜡笔的小新
    2020-12-12 21:21

    example: iOS 11 Swift 4

    override func viewDidLoad() {
        super.viewDidLoad()
    
        // Get the back-facing camera for capturing videos
    
        // AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back)
        let deviceDiscoverySession = AVCaptureDevice.default(.builtInWideAngleCamera, for: AVMediaType.video, position: .back)
    
       guard let captureDevice = deviceDiscoverySession else {
           print("Failed to get the camera device")
           return
       }
    
        do {
            // Get an instance of the AVCaptureDeviceInput class using the previous device object.
            let input = try AVCaptureDeviceInput(device: captureDevice)
    
            // Set the input device on the capture session.
            captureSession.addInput(input)
    
        } catch {
            // If any error occurs, simply print it out and don't continue any more.
            print(error)
            return
        }
    
        // Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
        videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
        videoPreviewLayer?.frame = view.layer.bounds
        view.layer.addSublayer(videoPreviewLayer!)
    
        // Start video capture.
        captureSession.startRunning()
    

提交回复
热议问题