0

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.

4

1 回答 1

2

好的。我终于找到了解决方案。在 iOS 6.0 中,苹果提供了一个新的函数调用 setCategory:withOptions:。这行得通。所以代码是这样的:

    AVAudioSession *session =[AVAudioSession sharedInstance];
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version <6.0) {
        [session setCategory:AVAudioSessionCategoryAmbient error:nil];
    }
    else {
        [session setCategory: AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error: nil];
    }

谢谢。

于 2012-12-23T23:02:41.720 回答