进入后台时停止摄像机录制并保存文件

Mic*_*iel 5 camera ios avcapturesession avcapturemoviefileoutput

我一直在寻找2天的答案,但我似乎无法做到正确......

我有一个示例应用程序,使用AVCaptureSession和AVCaptureMovieFileOutput从设备录制音频和视频.

当我开始录音时,我打电话:

[self.movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];
Run Code Online (Sandbox Code Playgroud)

它开始录制到文件中.如果我再次按下按钮则会停止录制

[self.movieFileOutput stopRecording];
Run Code Online (Sandbox Code Playgroud)

一切运作良好,但当我输入背景(来电或HOME按)时,我在委托方法中出错:didFinishRecordingToOutputFileAtURL

我想要的操作应该是在进入后台时保存/完成文件.如果我在"applicationDidEnterBackground"上调用stopRecording,它将在调用applicationDidEnterBackground之前进入后台.进入活动状态时,它被称为....并生成错误并留下损坏的电影文件...

它似乎没有足够的时间来保存文件.

我在这里错过了什么?

这是我的错误

Error Domain=AVFoundationErrorDomain Code=-11818 "Recording Stopped" UserInfo=0x17594e20 {NSLocalizedRecoverySuggestion=Stop any other actions using the recording device and try again., NSUnderlyingError=0x175d3500 "The operation couldn’t be completed. (OSStatus error -16133.)", NSLocalizedDescription=Recording Stopped}

AVErrorSessionWasInterrupted = -11818
Run Code Online (Sandbox Code Playgroud)

Mel*_*ram 3

NSOperationQueue是执行多线程任务以避免阻塞主线程的推荐方法。后台线程用于在应用程序处于非活动状态时执行的任务,例如 GPS 指示或音频流。

如果您的应用程序在前台运行,则根本不需要后台线程。

对于简单的任务,您可以使用块将操作添加到队列中:

NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init];
[operationQueue addOperationWithBlock:^{
    // Perform long-running tasks without blocking main thread
}];
Run Code Online (Sandbox Code Playgroud)

有关NSOperationQueue以及如何使用它的更多信息。

- (void)applicationWillResignActive:(UIApplication *)application {
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{

      // Wait until the pending operations finish
      [operationQueue waitUntilAllOperationsAreFinished];

      [application endBackgroundTask: bgTask];
      bgTask = UIBackgroundTaskInvalid;
    }]; 
}
Run Code Online (Sandbox Code Playgroud)