9.2. Handling 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 audioPlayerEndInterruption:withFlags:
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
withFlags:(NSUInteger)flags{
if (flags == AVAudioSessionInterruptionFlags_ShouldResume &&
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.
Note
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 deactivated. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access