On iPad, why does AVAudioSessionCategoryAmbient stop the music playing in iPod?

avfoundation, ios, iphone

Solution

As I said in my comment, it seems the solution is to set the AVAudioSession category BEFORE calling `prepareToPlay` on the AVAudioPlayer.

Problem

The following code is supposed to play a sound and won't stop the music playing by iPad's Music/iPod. (on iOS 5.1, the iPod app became the Music app). It is using `AVAudioSessionCategoryAmbient` instead of `AVAudioSessionCategorySoloAmbient`. But it actually stopped the music in either case. Is there something wrong with the use of `AVAudioSessionCategoryAmbient`? ``` NSURL *sound0URL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"0" ofType:@"aiff"]]; audioPlayer0 = [[AVAudioPlayer alloc] initWithContentsOfURL:sound0URL error:nil]; audioPlayer0.delegate = self; [audioPlayer0 prepareToPlay]; NSError *setCategoryErr = nil; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&setCategoryErr]; NSLog(@"%@", setCategoryErr); audioPlayer0.currentTime = 0; [audioPlayer0 play]; ``` the `setCategoryErr` is printed as `(null)` so there should be no error.

Original source