12.4. Playing Audio in the Background

Problem

You are writing an application that plays audio files (such as a music player) and you would like the audio files to be played even if your application is running in the background.

Solution

Create a new array key in your application’s main .plist file. Set the name of the key to UIBackgroundModes. Add the value audio to this new key. Here is an example of the contents of a .plist file with the aforementioned key and value added:

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

Now you can use the AV Foundation to play audio files, and your audio files will be played even if your application is in the background.

Discussion

In iOS, applications can request that their audio files continue playing even if the application is sent to the background. AV Foundation’s AVAudioPlayer is an easy-to-use audio player that we will use in this recipe. Our mission is to start an audio player and play a simple song, and while the song is playing, send the application to the background by pressing the Home button. If we have included the UIBackgroundModes key in our application’s .plist file, iOS will continue playing the music from our app’s audio player, even in the background. While in the background, we should only play music and provide our music player with the data that is necessary for it to run. We should not be performing any other tasks, such as displaying new screens.

Here is the .h file ...

Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.