陈斌彬的技术博客

Stay foolish,stay hungry

iOS - Handing Interruptions While Playing Audio

Problem

You want your AVAudioPlayer instance to resume playing after an interruption on an iOS device, such as an incoming call.

Solution

Implement the audioPlayerBeginInterruption: and audioPlayerEndInterrup tion:withOptions: methods of the AVAudioPlayerDelegate protocol in the delegate object of your AVAudioPlayer instance:

- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
/* Audio Session is interrupted. The player will be paused here */
}
- (void) audioPlayerEndInterruption:(AVAudioPlayer *)player
                           withOptions:(NSUInteger)flags{
if (flags == AVAudioSessionInterruptionOptionShouldResume && player != nil){
           [player play];
       }
}

Discussion

On an iOS device, such as an iPhone, a phone call could interrupt the execution of the foreground application. In that case, the audio session(s) associated with the application will be deactivated, and audio files will not be played until the interruption has ended. At the beginning and the end of an interruption, we receive delegate messages from the AVAudioPlayer informing us of the different states the audio session is passing through. After the end of an interruption, we can simply resume the playback of audio.

Tips:Incoming phone calls cannot be simulated with iPhone Simulator. You must always test your applications on a real device.

When an interruption occurs, the audioPlayerBeginInterruption: delegate method of an AVAudioPlayer instance will be called. Here your audio session has been deacti‐ vated. In case of a phone call, the user can just hear his ringtone. When the interruption ends (the phone call is finished or the user rejects the call), the audioPlayerEndInter ruption:withOptions: delegate method of your AVAudioPlayer will be invoked. If the withOptions parameter contains the value AVAudioSessionInterruptionOption ShouldResume, you can immediately resume the playback of your audio player using the play instance method of AVAudioPlayer.

Tips:The playback of audio files using AVAudioPlayer might show memory leaks in Instruments when the application is being run on iPhone Simulator. Testing the same application on an iOS device proves that the memory leaks are unique to the simulator, not the device. I strongly suggest that you run, test, debug, and optimize your applications on real devices before releasing them to the App Store.