Cover 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

O'Reilly logo

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

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