立即使用AVCaptureMovieFileOutput开始视频录制 [英] Starting video recording immediately with AVCaptureMovieFileOutput

查看:92
本文介绍了立即使用AVCaptureMovieFileOutput开始视频录制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的应用启动时使用 AVCaptureMovieFileOutput 将设备相机记录到视频文件中.令我沮丧的是,我无法正常工作:

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:

  • 我可以使用 AVCaptureVideoPreviewLayer 观看视频供稿,因此我的会话已正确连接.

  • 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.

API调用或通过 AVCaptureSessionRuntimeError 通知未返回错误.

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

我的 AVCaptureFileOutputRecordingDelegate 方法根本没有被调用.

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.

推荐答案

事实证明,您无法立即开始记录到这样的文件中:

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)

这将静默失败,什么也不做!

相反,您需要通过注册 AVCaptureSessionDidStartRunning 通知来等待会话开始:

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)
        }
    }
}

这篇关于立即使用AVCaptureMovieFileOutput开始视频录制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆