Playing Sound in the Background

In the multitasking world of iOS 4, when the user switches away from your app to another app, by default, your audio session is interrupted and your app is suspended. But if the business of your app is to play sound, you might like your app to continue playing sound in the background. In earlier sections of this chapter, I’ve spoken about how your app, in the foreground, relates its sound production to background sound such as the iPod/Music app. Now we’re talking about how your app can be that background sound, possibly playing sound while some other app is in the foreground.

To play sound in the background, your app must do two things:

  • In your Info.plist, you must include the “Required background modes” key (UIBackgroundModes) with a value that includes “App plays audio” (audio).
  • Your audio session’s policy must be Playback (and must be active, of course).

That’s actually all it takes! If those two things are true, then if your app is producing sound, that sound will go right on playing when the user clicks the Home button and dismisses your application or switches to another app.

An extremely cool feature of playing sound in the background is that remote control events continue to work. Even if your app was not actively playing at the time it was put into the background, if it is the remote control target, then if the user causes a remote control event to be sent, your app will be woken up in the background in order to receive it and can begin playing ...

Get Programming iOS 4 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.