我有这种情况:
在后台,默认的iPhone音频播放器(或任何其他音频播放器)正在播放一些音乐。 在前台我的应用程序正在运行。然后,在某些情况下,我的应用程序必须播放音频文件(有点像GPS导航器)。 我希望我的应用程序暂停后台播放器(躲避是不够的),播放其文件然后继续播放后台播放器。 这可能吗?
谢谢你, donescamillo@gmail.com
答案 0 :(得分:8)
从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];
来自Apple的文档 -
当传入setActive:withOptions:error:instance方法的flags参数时,表示当您的音频会话停用时,会话中断的其他音频会话可以返回其活动状态。 此标志仅在取消激活音频会话时使用;也就是说,当您在setActive的beActive参数中传递NO值时:withOptions:error:instance method
并且 -
如果当前正在运行任何关联的音频对象(例如队列,转换器,播放器或录像机),则取消激活会话将失败。
编辑:一个更详细的例子 -
在应用程序生命周期的开始配置可混合音频会话
// deactivate session
BOOL success = [[AVAudioSession sharedInstance] setActive:NO error: nil];
if (!success) { NSLog(@"deactivationError"); }
// set audio session category AVAudioSessionCategoryPlayAndRecord
success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
if (!success) { NSLog(@"setCategoryError"); }
// set audio session mode to default
success = [[AVAudioSession sharedInstance] setMode:AVAudioSessionModeDefault error:nil];
if (!success) { NSLog(@"setModeError"); }
// activate audio session
success = [[AVAudioSession sharedInstance] setActive:YES error: nil];
if (!success) { NSLog(@"activationError"); }
如果您的应用程序想要在没有播放任何背景音频的情况下输出音频,请首先更改音频会话类别
// activate a non-mixable session
// set audio session category AVAudioSessionCategoryPlayAndRecord
BOOL success;
AVAudioSessionCategoryOptions AVAudioSessionCategoryOptionsNone = 0;
success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionsNone error:nil];
if (!success) { NSLog(@"setCategoryError"); }
// set audio session mode default
success = [[AVAudioSession sharedInstance] setMode:AVAudioSessionModeDefault error:nil];
if (!success) { NSLog(@"setModeError"); }
// activate audio session
success = [[AVAudioSession sharedInstance] setActive:YES error: nil];
if (!success) { NSLog(@"activationError"); }
// commence playing audio here...
当您的应用程序完成播放音频后,您可以停用音频会话
// 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"); }
我可以确认上述代码是有效的,使用 iPhone 5 在 iPhone 5 上运行 iOS 7.0.4 进行测试,但是这是不可保证的,因为还有其他考虑因素,例如用户操作。例如,如果我插入耳机,音乐应用程序中的背景音频会路由到耳机并继续播放,但如果我移除耳机,音乐应用程序产生的背景音频会暂停。
有关更多信息,请阅读AVAudioSession类参考