如何在Swift中从Session中捕获视频?

时间:2016-12-13 15:25:50

标签: ios iphone swift

我有一个标准的视图控制器,它使用捕获会话并预览相机所看到的内容。现在我有了这个,我想要我执行动作的按钮(在底部的saveVideo动作中)并开始录制视频。实际保存输出帧需要什么样的代码?

import UIKit
import AVFoundation

class ViewController: UIViewController {


    var captureSession = AVCaptureSession();
    var sessionOutput = AVCaptureVideoDataOutput();
    var previewLayer = AVCaptureVideoPreviewLayer();


    override func viewDidAppear(_ animated: Bool) {
        captureSession.startRunning()
    }


    override func viewWillAppear(_ animated: Bool) {
         let deviceDiscoverySession = AVCaptureDeviceDiscoverySession(deviceTypes: [AVCaptureDeviceType.builtInDuoCamera, AVCaptureDeviceType.builtInTelephotoCamera,AVCaptureDeviceType.builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: AVCaptureDevicePosition.back)

    for device in (deviceDiscoverySession?.devices)!{
        if(device.position == AVCaptureDevicePosition.back){

            do{
                let input = try AVCaptureDeviceInput(device: device )

                if captureSession.canAddInput(input){

                    captureSession.addInput(input)

                }

               // sessionOutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString) : NSNumber(value: kCVPixelFormatType_420YpCbCr8BiPlanarFullRange as UInt32)]

                sessionOutput.alwaysDiscardsLateVideoFrames = true

                if(captureSession.canAddOutput(sessionOutput) == true){
                    captureSession.addOutput(sessionOutput)

                    let previewLayer: AVCaptureVideoPreviewLayer = {
                        let preview =  AVCaptureVideoPreviewLayer(session: self.captureSession)
                        preview?.bounds = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)
                        preview?.position = CGPoint(x: self.view.bounds.midX, y: self.view.bounds.midY)
                        preview?.videoGravity = AVLayerVideoGravityResize
                        return preview!
                    }()

                    view.layer.insertSublayer(previewLayer, at: 0)



                }

                captureSession.commitConfiguration()

            }

            catch{
                print("Error")
            }


        }

    }


}

    @IBAction func saveVideo(_ sender: Any) {
    }
}

1 个答案:

答案 0 :(得分:1)

您需要将AVSession的委托设置为ViewController,然后调用将在会话的不同状态下触发的委托方法。

有关详细信息,请参阅https://developer.apple.com/reference/avfoundation/avcapturesession

具体的captureOutput委托方法将从您的ViewController中的委托中调用。