Search code examples
iphoneaudiobackgroundrecording

iPhone AVAudioRecorder pause problem after entering background


I have a problem with pausing AVAudioRecorder after entering background. Basically, it goes like this (_recorder is my AVAudioRecorder instance):

  1. Start recording:

    [_recorder record];
    
  2. Press the home button on the device.

  3. Because I've set observer for notification of this case (in viewDidLoad), my custom method applicationDidEnterBackground fires.
  4. In applicationDidEnterBackground I do:

    [_recorder pause];
    
  5. Now, when I tap application icon, to take app to foreground, recording continous immediately, without taking any action. It's even stranger, because checking property:

    _recorder.recording == YES
    

returns NO.

I have a function, that is called by NSTimer every 0.1s (to refresh UI etc.), and in that function I have this:

if(_recorder.recording) {
    NSLog(@"recording");
}
else {
    NSLog(@"not recording");
    NSLog(@"time: %f", _recorder.currentTime);
} 

It prints on the console:

    ...
    not recording
    time: 9.404082
    not recording
    not recording
    time: 9.473197
    not recording
    time: 9.531179
    not recording
    time: 9.629206
    not recording
    time: 9.728435
    ...

So, as you can see, the recorder's currentTime increases all the time, and the audio is being recorded.

Any Idea how to solve this?


Solution

  • You should add the following code:

    <key>UIBackgroundModes</key>
    <array>
        <string>audio</string>
    </array>
    

    to the Info.plist. This will cause the background mode to be responsive for managing audio session, so you can manually pause and resume recording.