如何在Swift中录制带有avfoundation的视频?

时间:2015-10-21 00:32:05

标签: ios swift avfoundation video-capture

我想弄清楚如何在Swift中使用AVFoundation录制视频。我已经创建了一个自定义相机,但我只知道如何使用它拍摄静态图片,我无法弄清楚如何录制视频。根据我的理解,您必须使用AVCaptureVideoDataOutput从录制中获取数据,但我无法弄清楚如何开始录制并实现委托方法。

整个AVFoundation编程指南/静止和视频媒体捕获是在Objective-C中,我似乎无法解读它。这是我完成这项任务的尝试:

首先我设置了相机/捕获会话

override func viewDidLoad() {
    super.viewDidLoad()

    captureSession.sessionPreset = AVCaptureSessionPresetHigh
    let devices = AVCaptureDevice.devices()
    for device in devices {
        if (device.hasMediaType(AVMediaTypeVideo)) {
            if(device.position == AVCaptureDevicePosition.Back) {
                captureDevice = device as? AVCaptureDevice
                if captureDevice != nil {
                    beginSession()
                }
            }
        }
    }

}

然后,一旦调用了beginSession(),我就设置了实时提要

func beginSession() {
    var err : NSError? = nil
    captureSession.addInput(AVCaptureDeviceInput(device: captureDevice, error: &err))
    if err != nil {
        println("error: \(err?.localizedDescription)")
    }
    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    self.cameraView.layer.addSublayer(previewLayer)
    self.cameraView.bringSubviewToFront(takePhotoButton)
    self.cameraView.bringSubviewToFront(self.snappedPicture)
    self.cameraView.bringSubviewToFront(self.backButton)
    previewLayer?.frame = self.cameraView.layer.frame
    captureSession.startRunning()
}

在这里我被困在用户按下记录以实际录制和捕捉视频的位置:

@IBAction func takeVideoAction(sender: AnyObject) {

    var recordingDelegate:AVCaptureFileOutputRecordingDelegate? = self

    var videoFileOutput = AVCaptureMovieFileOutput()
    self.captureSession.addOutput(videoFileOutput)

    let filePath = NSURL(fileURLWithPath: "filePath")

    videoFileOutput.startRecordingToOutputFileURL(filePath, recordingDelegate: recordingDelegate)

}

然后我致电self.videoFileOutput.stopRecording()

然后是委托方法

func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
    return
}

func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) {
    return
}

没有任何事情可以想象,因为我无法弄清楚如何正确实现它。

1 个答案:

答案 0 :(得分:14)

我已经尝试过您的代码了。设置有意义的filePath时,一切都很顺利。像这样更改filePath,您将调用委托方法:

    let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    let filePath = documentsURL.URLByAppendingPathComponent("temp")

    // Do recording and save the output to the `filePath`
    videoFileOutput.startRecordingToOutputFileURL(filePath, recordingDelegate: recordingDelegate)
相关问题
最新问题