O'Reilly logo

iOS 5 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required