16.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
Select your project file in the Navigator of Xcode. Then, from the Capabilities section, switch on the Background Modes subsection. After the list of background modes is given to you, tick on the Audio switch.
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.
Note
Please bear in mind that playing audio in the background might not work in iOS Simulator. You need to test this recipe on a real device. On the simulator, chances are that the audio will stop playing once your application is sent to 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 employ 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 you have successfully enabled the Audio
background mode (as explained in the Solution of this recipe) in our target, 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 ...
Get iOS 7 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.