且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iOS应用程序在后台录制时音频中断

更新时间:2022-04-28 03:44:20

我自己也遇到过同样的问题.似乎 iOS7 AVAudioRecorder 在处理中断方面存在错误.它没有像我认为文档所说的那样暂停,而是关闭了文件.当应用程序回到前台时,我无法弄清楚是什么导致了应用程序的停滞.就我而言,我会在 10 秒后看到 AVAudioRecorder 完成(成功标志设置为 NO).

I have been going through the same issue myself. It seems as if there is a bug in the iOS7 AVAudioRecorder in how it deals with interrupts. Instead of pausing as I believe the documentation says that is should, it closes the file. I have not been able to figure out what is stalling the app when it comes back to the foreground. In my case, I would see AVAudioRecorder finish (with the success flag set to NO), after 10 seconds.

我最终使用音频队列重写了录音机.我在这里找到了一些示例代码(git@github.com:vecter/Audio-Queue-Services-Example.git),它们有助于在 Objective-C 环境中进行设置,Apple SpeakHere 演示有一些代码来处理中断通知.

I ended up rewriting the audio recorder using Audio Queues. I found some sample code here (git@github.com:vecter/Audio-Queue-Services-Example.git) that helped with setting it up in an Objective-C environment and the Apple SpeakHere demo has some code to handle the interrupt notifications.

基本上,我会在中断开始时停止录制并打开警报以供用户保存文件.如果在应用程序处于后台时启动中断,则此警报将延迟到 UIApplicationDidBecomeActiveNotification 传递.

Essentially, I am stopping the recording on interrupt began and opening an alert for the user to save the file. This alert is deferred until UIApplicationDidBecomeActiveNotification is passed if the interrupt started while the app was in the background.

另外需要注意的是,音频队列中似乎存在一个小错误,即 AudioQueueStart 方法有时会返回 -50.如果你添加

One other thing to note, there seems to be a minor bug in Audio Queues that the AudioQueueStart method will return -50 sometimes. If you add

AudioSessionInitialize(NULL, NULL,nil,(__bridge  void *)(self));
UInt32 sessionCategory = kAudioSessionCategory_PlayAndRecord;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,
                        sizeof(sessionCategory),
                        &sessionCategory
                        );
AudioSessionSetActive(true);

在任何 AudioQueue 方法之前,错误都会消失.这些方法被标记为已弃用,但似乎是必需的.

Before any AudioQueue methods, the error goes away. These methods are marked as deprecated but seem to be necessary.