进入背景时停止相机录制并保存文件



我已经找了两天的答案,但似乎找不到正确的答案。。。

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

当我开始录音时,我会呼叫:

[self.movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];

然后它开始录制到文件中。如果我再次按下按钮,它将停止记录

[self.movieFileOutput stopRecording];

一切都很好,但当我进入后台(来电或主页)时,我在委托方法中遇到了一个错误: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

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

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

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

NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init];
[operationQueue addOperationWithBlock:^{
    // Perform long-running tasks without blocking main thread
}];

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

- (void)applicationWillResignActive:(UIApplication *)application {
    bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
      // Wait until the pending operations finish
      [operationQueue waitUntilAllOperationsAreFinished];
      [application endBackgroundTask: bgTask];
      bgTask = UIBackgroundTaskInvalid;
    }]; 
}

您可以在applicationWillResignActive:中处理保存,然后可以在后台继续处理。

最新更新