AVAudioPlayer在iOS 6.0.1中无法在AVAudioSessionCategoryAmbient模式下工作?

时间:2012-12-23 12:56:27

标签: avaudioplayer mpmusicplayercontroller

在我的应用程序中,我使用MPMusicPlayerController播放.mp3作为背景音乐, 和AVAudioPlayer播放声音效果,就像按下按钮一样,等等。 代码是这样的:

// 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在播放结束后发布。

该代码适用于iOS 5.0。但在iOS 6.0中,一切都发生了变化。 无论如何AVAudioPlayer都不播放声音。

如果我更改此行:     [session setCategory: AVAudioSessionCategoryAmbient 错误:nil]; 至:     [session setCategory: AVAudioSessionCategoryPlayback 错误:nil];

AVAudioPlayer将播放声音,但它将打破MPMusicPlayerController的播放会话... 我怎样才能找到一种播放AVAudioPlayer但不打破背景音乐的方法?非常感谢你的帮助。

1 个答案:

答案 0 :(得分:2)

行。我终于找到了解决方案。在iOS 6.0中,apple提供了一个新函数调用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];
    }

感谢。