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

Posted

技术标签:

【中文标题】进入后台时停止相机录制并保存文件【英文标题】:Stop Camera recording and save file when entering background 【发布时间】:2013-12-16 12:29:05 【问题描述】:

我一直在寻找答案 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

【问题讨论】:

我也试过 Apple AVDemo 应用程序,它也给出了同样的错误。似乎无论如何都会抛出错误。不同之处在于,在 Apple 的代码中,他们有时间使用 UIBackgroundTaskIdentifier 执行大量代码 【参考方案1】:

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

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

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

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;
    ]; 

【讨论】:

这就是我要走的路。我确实从 Apples 的示例代码中实现了这段代码,但我犯了一个愚蠢的错误......每次保存电影时文件扩展名都会改变,因此对我来说看起来已经损坏 -1......【参考方案2】:

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

【讨论】:

那不行,我必须确保会话在进入后台时不会被中断。 那么你必须创建另一个线程......当它进入后台时你必须处理那个线程...... 检查一下,applicationWillResignActive 没有给我足够的时间来处理。在 Melih Büyükbayram 中确实如此! @Michiel 我想说同样的话。我看不到他的回答。

以上是关于进入后台时停止相机录制并保存文件的主要内容,如果未能解决你的问题,请参考以下文章

是否可以在录制时检查视频的大小?注意:(我没有使用本机相机应用程序。)

将录制的音频保存在文档目录中并创建一个包含所有音频文件的数据库

在使用 AVAudioRecorder 在为导航栏设置动画的同时录制音频时发生中断时,我们如何停止并保存录制?

如何更改录制音频的音高并在后台保存?

怎么在psd中做寸照动作并在保存下来

在后台写入日志文件