【问题标题】:AVAudioPlayer don't work in AVAudioSessionCategoryAmbient mode in iOS 6.0.1?AVAudioPlayer 在 iOS 6.0.1 的 AVAudioSessionCategoryAmbient 模式下不起作用?
【发布时间】:2012-12-23 12:56:26
【问题描述】:

在我的应用程序中,我使用 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 无论如何都不播放声音。

如果我改变这一行: [会话 setCategory:AVAudioSessionCategoryAmbient 错误:无]; 到: [会话 setCategory:AVAudioSessionCategoryPlayback 错误:无];

AVAudioPlayer 会播放声音,但会中断 MPMusicPlayerController 的播放会话... 如何找到播放 AVAudioPlayer 但不破坏背景音乐的方法?非常感谢您的帮助。

【问题讨论】:

    标签: avaudioplayer mpmusicplayercontroller


    【解决方案1】:

    好的。我终于找到了解决方案。在 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];
        }
    

    谢谢。

    【讨论】:

      猜你喜欢
      • 2014-11-25
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多