Starting video recording immediately with AVCaptureMovieFileOutput

孤街浪徒 提交于 2020-08-23 21:33:41

问题


I was trying to use AVCaptureMovieFileOutput to record the device camera to a video file when my app starts. To my great frustration, I could not get it to work:

  • I could view the video feed using a AVCaptureVideoPreviewLayer just fine, so my session was wired up properly.

  • The file to which it would output did not already exist, and was in a writable directory.

  • No errors were returned from API calls or via AVCaptureSessionRuntimeError notifications.

  • My AVCaptureFileOutputRecordingDelegate methods were not called at all.

I tried sample code after sample code, and more maddeningly some of them seemed to actually work.


回答1:


It turns out that you cannot immediately start recording to the file like this:

let session = AVCaptureSession() 
session.beginConfiguration()
// add inputs, outputs
session.commitConfiguration()
videoFileOutput.startRecording(to: filePath, recordingDelegate: self)

This will silently fail and do nothing at all!

Instead, you need to wait for the session to start by registering for the AVCaptureSessionDidStartRunning notification:

NotificationCenter.default.addObserver(self, selector: #selector(sessionDidStartRunning), name: .AVCaptureSessionDidStartRunning, object: session)

You can implement this method as follows to start recording to a temporary file immediately after the session begins:

@objc
func sessionDidStartRunning(notification: NSNotification) {
    let session = notification.object as! AVCaptureSession
    for output in session.outputs {
        if let output = output as? AVCaptureMovieFileOutput {
            let filePath = URL(fileURLWithPath: NSTemporaryDirectory() + "recording.mov")
            try? FileManager.default.removeItem(at: filePath)
            output.startRecording(to: filePath, recordingDelegate: self)
        }
    }
}


来源:https://stackoverflow.com/questions/47930836/starting-video-recording-immediately-with-avcapturemoviefileoutput

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!