In my app, I use a MPMusicPlayerController play .mp3 as background music, and an AVAudioPlayer play sound-effect, just like button press, and so on. The code is like this:
// Initialization code here.
AudioSessionInitialize(NULL, NULL, NULL, NULL);
AVAudioSession *session =[AVAudioSession sharedInstance];
//The background music and the sound-effect can play simultaneously
[session setCategory: AVAudioSessionCategoryAmbient error:nil];
[session setActive: YES error: nil];
m_sharedPlayer = [[MPMusicPlayerController applicationMusicPlayer] retain];
[m_sharedPlayer setShuffleMode: MPMusicShuffleModeSongs];
[m_sharedPlayer setRepeatMode: MPMusicRepeatModeAll];
[m_sharedPlayer setVolume:0.2];
// choose the first song
[m_sharedPlayer setQueueWithQuery: [MPMediaQuery songsQuery]];
[m_sharedPlayer play];
...
//when need play sound-effect, soundfilename is a NSString
NSData *data =[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:soundfilename ofType:nil]];
AVAudioPlayer *audioplayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
audioplayer =1.0;
audioplayer.delegate =self;
[audioplayer prepareToPlay];
[audioplayer play];
...
audioplayer is release after it has finished play.
The code is work in iOS 5.0. But in iOS 6.0, everything changed. AVAudioPlayer don't play sound anyway.
If I change this line: [session setCategory: AVAudioSessionCategoryAmbient error:nil]; To: [session setCategory: AVAudioSessionCategoryPlayback error: nil];
The AVAudioPlayer will play sound, but it will break the play session of MPMusicPlayerController... How can I find a way to play AVAudioPlayer but without break the background music? Thanks a lot for your help.