AVAudioPlayer, using AmbientSound session, is not playing when app is in background

1.9k views Asked by At

If this is in the apple doc then I've not been able to find it - hoping someone can help:

My app plays occasional short audio clips - I want the audio to mix in with audio playing from other apps in the background like the iPod app - but I also want it to carry on playing these audio clips when the app is running in background.

I have set "App plays audio" in the Required Background Modes settings in info.plist (the app is also using location services too so that is also set in there)

My app sets up an audio session on applicationDidFinishLaunching:

AudioSessionInitialize (NULL,NULL,NULL,NULL);
UInt32 sessionCategory = kAudioSessionCategory_AmbientSound;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,sizeof (sessionCategory),&sessionCategory); 
AudioSessionSetActive(true);

In my viewWillAppear: method in the view that is active I have:

[super viewWillAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder]; 

and the corresponding event handler and endReceivingRemoteControlEvents code in viewWillDisappear: as discussed in iOS 4: Remote controls for background audio

Finally I have an AVAudioPlayer, set up in the normal way, that plays a sound on certain events

bool successful = [avAudioPlayer play];
if(!successful)
    NSLog(@"did not play");

When the app is in foreground the app works fine and plays the audio - but when the app goes into background and the app attempts to play a sound the return value from the [avAudioPlayer play] is NO and the sound does not play - when switched back to foreground the audio starts working again.

If when I set up the session I instead use

    UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;

Then the audio plays in foreground and background perfectly. But MediaPlayback is not the really the right mode for this app since I am only occasionally playing audio clips - AmbientSound is really the mode I should be using.

What am I missing? Is it just not possible to use kAudioSessionCategory_AmbientSound to play Audio in the background? If so I've not found anything in the documentation about that.

1

There are 1 answers

2
Simon East On BEST ANSWER

Had to submit a tech support request for this in the end.

According to Apple background playback is not supported by the AmbientSound category - you have to use MediaPlayback.

They claim this is in the documentation - I've looked again and I could not find it.

Ok so getting background sounds to mix into MediaPlayback is easy enough using kAudioSessionProperty_OverrideCategoryMixWithOthers - but I am now going to have to jump through some other hoops to replicate the other AmbientSound functionality (obeying the mute switch and not playing when locked). I really don't understand why AmbientSound is not supported playing in background - but there we go.