提交工单
咨询集成、功能及报价等问题
使用 ZegoAudioRoom SDK 直播过程中,可能会被来电、切后台等事件打断,此时开发者需要处理打断事件。
SDK 提供了与音频打断事件相关的API,如下所示:
ZegoAudioRoomApi.h
/**
暂停模块
@attention 用于需要暂停指定模块的场合,例如来电时暂定音频模块
@note 暂停指定模块后,注意在合适时机下恢复模块
*/
- (void)pauseAudioModule;
ZegoAudioRoomApi.h
/**
恢复模块
@attention 用于需要恢复指定模块的场合,例如来电结束后恢复音频模块
@note 暂停指定模块后,注意在合适时机下恢复模块
*/
- (void)resumeAudioModule;
本文以来电和切后台为例,讲述如何处理打断事件。
开发者需要在合适的 ViewController 中或其他位置,监听音频打断事件。
示例代码片段如下:
// 监听电话事件
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(audioSessionWasInterrupted:)
name:AVAudioSessionInterruptionNotification
object:nil];
音频打断处理一般有两个步骤:
示例代码片段如下:
- (void)audioSessionWasInterrupted:(NSNotification *)notification
{
NSLog(@"%s: %@", __func__, notification);
if (AVAudioSessionInterruptionTypeBegan == [notification.userInfo[AVAudioSessionInterruptionTypeKey] intValue])
{
// 暂停音频设备
[[ZegoDemoHelper api] pauseAudioModule];
}
else if(AVAudioSessionInterruptionTypeEnded == [notification.userInfo[AVAudioSessionInterruptionTypeKey] intValue])
{
// 恢复音频设备
[[ZegoDemoHelper api] resumeAudioModule];
}
}
Apple 官方示例详见: MusicCube
如果开发者希望 App 退至后台依然支持音频播放、录制,需要先在项目中开启后台模式,并指定模式为 Audio,AirPlay,and Picture in Picture
,如图所示:
设置后,Xcode 会自动在项目的 Info.plist 中添加对应条目 Required background modes
: App plays audio or streams audio/video using AirPlay
。
开启此选项,当应用退至后台,只要有音频播放、录制行为,就可以一直运行。运行时,状态栏会变成红色,指示用户当前有麦克风设备在后台运行。
Apple 官方指导详见: Background Execution
开发者开启后台模式,如果在某些场景下需要在后台停止音频播放或录制,依然可以使用 pauseAudioModule
resumeAudioModule
实现。
对于 App 切换前后台行为的监听,有两种常用方式:
// 监听 App 切后台
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(appDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
// 监听 App 从后台切前台
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(appWillEnterForeground:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
在上述方法中,停止后台播放音频的步骤为:
pauseAudioModule
暂停音频模块。resumeAudioModule
恢复音频模块。联系我们
文档反馈