Detecting When Music is Playing in iOS 8

Ideally, games should not play their soundtrack when another app is playing music in the background.

To help us detect when another app is playing audio, Apple introduced the AVAudioSession.isOtherAudioPlaying property in iOS 6. This property will be set to YES while other apps play audio.

As of iOS 8, Apple recommends using a new property named secondaryAudioShouldBeSilencedHint.

AVAudioSession *audionSession = [AVAudioSession sharedInstance];
if (audionSession.secondaryAudioShouldBeSilencedHint) {
    // Silence...
} else {
    // Play soundtrack!

Detecting Changes

You might be asking yourself, “what if the music starts or stops while the user plays the game?” Enter AVAudioSessionSilenceSecondaryAudioHintNotification.

Your game can subscribe to AVAudioSessionSilenceSecondaryAudioHintNotification and be notified whenever other apps start or stop playing audio in the background.

[[NSNotificationCenter defaultCenter] addObserver:self

To glue everything together I recommend creating a “Soundtrack Manager” singleton class. The class should be responsible for playing the looping audio files that make the soundtrack, registering itself for secondary audio hint notification changes, and starting stopping the music accordingly.