If this is in the apple document, I could not find it - I hope someone can help:
My application plays short short audio clips - I want the sound to mix with audio games from other applications in the background, such as iPod, but I also want it to continue playing these audio clips when the application is running in the background.
I installed "App play audio" in the "Required background modes" settings in the info.plist file (the application also uses location services so that it is also installed)
My application sets up an audio session to applicationDidFinishLaunching:
AudioSessionInitialize (NULL,NULL,NULL,NULL); UInt32 sessionCategory = kAudioSessionCategory_AmbientSound; AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,sizeof (sessionCategory),&sessionCategory); AudioSessionSetActive(true);
In my view, WillAppear: method in active view:
[super viewWillAppear:animated]; [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; [self becomeFirstResponder];
and the corresponding event handler and endReceivingRemoteControlEvents code in viewWillDisappear: as discussed in iOS 4: Remote control for background sound
Finally, I have AVAudioPlayer configured in the usual way that plays sound on specific events
bool successful = [avAudioPlayer play]; if(!successful) NSLog(@"did not play");
When the application is in the foreground, the application works fine and plays audio, but when the application goes into the background and the application tries to play the sound, the return value from [avAudioPlayer play] is NO and the sound does not play - when switching to the foreground, the sound again starts working.
If, when setting up a session, I use instead
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
Then the sound is played in the foreground and in the background. But MediaPlayback is not the right mode for this application, since I only play audio clips from time to time - AmbientSound is really the mode I should use.
What am I missing? Can I use kAudioSessionCategory_AmbientSound to play audio in the background? If so, I did not find anything in the documentation about this.