如何在iOS中暂停后台播放器



我有这样的场景:

在后台,默认的iPhone音频播放器(或任何其他音频播放器)正在播放一些音乐。在前台,我的应用程序正在运行。然后,在某些情况下,我的应用程序必须播放音频文件(有点像GPS导航器)。我希望我的应用程序暂停背景播放器(回避是不够的),播放其文件,然后继续播放背景播放器。这可能吗?

谢谢,donescamillo@gmail.com

从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:instance方法的flags参数时,表示当您的音频会话停用时,被您的会话中断的其他音频会话可以恢复到活动状态。此标志仅在停用音频会话时使用;也就是说,当您在setActive:withOptions:error:instance方法的beActive参数中传递NO值时

以及-

如果任何关联的音频对象(如队列、转换器、播放器或录音机)当前正在运行,则停用会话将失败。

EDIT:一个更详细的例子-

在应用程序生命周期开始时配置可混合的音频会话

// 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"); }

我可以确认,在运行iOS 7.0.4iPhone 5上播放的音乐应用程序测试了上述代码,但这并不能保证,因为还有其他考虑因素,如用户操作。例如,如果我插入耳机,音乐应用程序的背景音频会路由到耳机并继续播放,但如果我拔下耳机,则音乐应用程序产生的背景音频将暂停。

有关更多信息,请阅读AVAudioSession类参考

最新更新