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

时间:2013-12-16 12:29:06

标签: ios camera avcapturesession avcapturemoviefileoutput

我一直在寻找2天的答案,但我似乎无法把它弄好......

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

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

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

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

[self.movieFileOutput stopRecording];

一切运作良好,但是当我输入背景(来电或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

2 个答案:

答案 0 :(得分:3)

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

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

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

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

有关NSOperationQueuehow to use it的更多信息。

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

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

      [application endBackgroundTask: bgTask];
      bgTask = UIBackgroundTaskInvalid;
    }]; 
}

答案 1 :(得分:1)

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