10.5. Playing Audio over Other Active Sounds

Problem

You either want to put other applications in silent mode while you play audio or play audio on top of other applications’ audio playback (if any).

Solution

Use audio sessions to set the type of audio category your application uses.

Discussion

The AVAudioSession class was introduced in the AV Foundation framework. Every iOS application has one audio session. This audio session can be accessed using the sharedInstance class method of the AVAudioSession class, like so:

AVAudioSession *audioSession = [AVAudioSession sharedInstance];

After retrieving an instance of the AVAudioSession class, you can invoke the setCategory:error: instance method of the audio session object to choose among the different categories available to iOS applications. Different values that can be set as the audio session category of an application are listed here:

AVAudioSessionCategoryAmbient

This category will not stop the audio from other applications, but it will allow you to play audio over the audio being played by other applications, such as the Music app. The main UI thread of your application will function normally. The prepareToPlay and play instance methods of AVAudioPlayer will return with the value YES. The audio being played by your application will stop when the user locks the screen. The silent mode silences the audio playback of your application only if your application is the only application playing an audio file. If you start playing audio while the ...

Get iOS 6 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.