我有这个场景:
在后台,默认的 iPhone 音频播放器(或任何其他音频播放器)正在播放一些音乐。
在前台,我的应用程序正在运行。然后,在某些情况下,我的应用程序必须播放音频文件(有点像 GPS 导航器)。
我希望我的应用程序暂停后台播放器(闪避是不够的),播放其文件,然后继续播放后台播放器。
这可能吗?
谢谢,
donescamillo@gmail.com
最佳答案
从 iOS 6 开始,您可以将 Audio Session 设置为事件状态,播放您的文件,然后使用 AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation 标志使用选项停用您的 session 。确保在需要播放音频时设置不可混合的类别,以便背景音频停止。
在简单的步骤 -
// 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 的文档——
并且-
编辑:一个更详细的例子 -
在应用程序生命周期开始时配置可混合 Audio Session
// 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"); }
当您的应用程序想要在没有任何背景音频播放的情况下输出音频时,请先像这样更改 Audio Session 类别
// 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...
当您的应用程序完成播放音频时,您可以停用 Audio Session
// 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 上进行了测试,但是这不能保证,因为还有其他考虑因素,例如用户操作。例如,如果我插入耳机,音乐应用程序的背景音频会路由到耳机并继续播放,但如果我移除耳机,音乐应用程序产生的背景音频会暂停。
有关更多信息,请阅读 AVAudioSession 类引用
关于ios - 如何在 iOS 中暂停后台播放器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20993360/