从iOS 6开始,您可以使用选项设置您的音频会话为活动状态,播放您的文件,然后使用AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation标志停用您的会话。确保在需要播放音频时设置非混合类别,以停止背景音频。
简单来说,您可以按以下步骤操作:
// Configure audio session category and activate ready to output some audio
[[AVAudioSession sharedInstance] setActive:YES error:nil]
// Play some audio, then when completed deactivate the session and notify other sessions
[[AVAudioSession sharedInstance] setActive:NO withOptions: AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil]
从苹果的文档中可以得知:当在setActive:withOptions:error:实例方法的flags参数中传递时,表示当您的音频会话停用时,由您的会话中断的其他音频会话可以返回其活动状态。该标志仅在停用您的音频会话时使用;也就是说,当您在setActive:withOptions:error:实例方法的beActive参数中传递NO值时。
此外,如果任何关联的音频对象(如队列、转换器、播放器或录音机)正在运行,则停用会话将失败。
编辑:以下是更详细的示例 -
在应用程序生命周期的开始配置可混合的音频会话。
BOOL success = [[AVAudioSession sharedInstance] setActive:NO error: nil];
if (!success) { NSLog(@"deactivationError"); }
success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
if (!success) { NSLog(@"setCategoryError"); }
success = [[AVAudioSession sharedInstance] setMode:AVAudioSessionModeDefault error:nil];
if (!success) { NSLog(@"setModeError"); }
success = [[AVAudioSession sharedInstance] setActive:YES error: nil];
if (!success) { NSLog(@"activationError"); }
当您的应用程序想要输出没有任何背景音频播放时,首先更改音频会话类别,如下所示:
更改音频会话分类
BOOL success;
AVAudioSessionCategoryOptions AVAudioSessionCategoryOptionsNone = 0;
success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionsNone error:nil];
if (!success) { NSLog(@"setCategoryError"); }
success = [[AVAudioSession sharedInstance] setMode:AVAudioSessionModeDefault error:nil];
if (!success) { NSLog(@"setModeError"); }
success = [[AVAudioSession sharedInstance] setActive:YES error: nil];
if (!success) { NSLog(@"activationError"); }
当您的应用程序完成播放音频后,您可以停用音频会话
// deactivate session and notify other sessions
// check and make sure all playing of audio is stopped before deactivating session...
BOOL success = [[AVAudioSession sharedInstance] setActive:NO withOptions: AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error: nil]
if (!success) { NSLog(@"deactivationError")
我确认上述代码可以工作,在运行iOS 7.0.4的
iPhone 5上测试了
Music App播放,但这并不保证,因为还有其他考虑因素,例如用户操作。例如,如果我插入耳机,则音乐应用程序的后台音频会路由到耳机并继续播放,但是如果我拔出耳机,则音乐应用程序产生的后台音频会暂停。
有关更多信息,请阅读AVAudioSession类参考文献。