问题
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