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

标签 ios camera avcapturesession avcapturemoviefileoutput

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

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

当我开始录音时,我调用:

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

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

[self.movieFileOutput stopRecording];

一切正常,但是当我进入后台(来电或按 HOME)时,委托(delegate)方法出现错误: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 "操作无法完成。( OSStatus 错误 -16133.)", NSLocalizedDescription=Recording Stopped}

AVErrorSessionWasInterrupted = -11818

最佳答案

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

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

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

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

关于 NSOperationQueue 的更多信息和 how to use it .

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

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

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

关于ios - 进入后台时停止摄像头录像并保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20610995/

相关文章:

ios - 我们可以快速从基类访问重写的类函数吗?

ios - Xcode 10 'frame' is only available on iOS 12.0 or newer 编译错误 iOS 12 beta

ios - NSStream NSStreamEventHasSpaceAvailable事件何时调用?

ios - 自定义相机 iOS

ios - 如何根据按下的 UIButton 重新填充表格 View ?

ios - 在iOS中,我们可以设置UIButton的字体和标题并获取其宽度吗?

textbox - 三.JS -- 场景中Camera控件与文本框冲突

ios - 在 iOS 上拍照后 Phonegap App 崩溃

android - 应用程序传递了 NULL 表面,同时在没有表面 View 的情况下拍照

ios - videoZoomFactor 不适用于 AVCaptureSession