直播打断事件处理(音视频SDK高级功能四)

本篇是即构科技音视频SDK高级功能第四篇,ZegoLiveRoom SDK 打断事件处理,以iOS环境为例。

1、简介

使用 ZegoLiveRoom SDK 直播过程中,可能会被来电、切后台等事件打断,此时开发者需要处理打断事件。

SDK 提供了与音频打断事件相关的API,如下所示:

ZegoLiveRoomApi.h

/**
 暂停模块

 @param moduleType 模块类型,参考 ZegoAPIModuleType 定义
 @attention 用于需要暂停指定模块的场合,例如来电时暂定音频模块
 @note 暂停指定模块后,注意在合适时机下恢复模块
 */
- (void)pauseModule:(int)moduleType;
ZegoLiveRoomApi.h

/**
 恢复模块

 @param moduleType 模块类型,参考 ZegoAPIModuleType 定义
 @attention 用于需要恢复指定模块的场合,例如来电结束后恢复音频模块
 @note 暂停指定模块后,注意在合适时机下恢复模块
 */
- (void)resumeModule:(int)moduleType;

本文以来电和切后台为例,讲述如何处理打断事件。

2、来电

2.1 监听音频打断事件

开发者需要在合适的 ViewController 中或其他位置,监听音频打断事件。

示例代码片段如下:

// 监听电话事件
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(audioSessionWasInterrupted:)
                                             name:AVAudioSessionInterruptionNotification
                                           object:nil];

2.2 处理音频打断

音频打断处理一般有两个步骤:

1.音频打断发生时,暂停音频设备

2.音频打断恢复后,恢复音频设备

示例代码片段如下:

- (void)audioSessionWasInterrupted:(NSNotification *)notification
{
    NSLog(@"%s: %@", __func__, notification);
    if (AVAudioSessionInterruptionTypeBegan == [notification.userInfo[AVAudioSessionInterruptionTypeKey] intValue])
    {
        // 暂停音频设备
        [[ZegoDemoHelper api] pauseModule:ZEGOAPI_MODULE_AUDIO];
    }
    else if(AVAudioSessionInterruptionTypeEnded == [notification.userInfo[AVAudioSessionInterruptionTypeKey] intValue])
    {
        // 恢复音频设备
        [[ZegoDemoHelper api] resumeModule:ZEGOAPI_MODULE_AUDIO];
    }
}

Apple 官方示例详见: MusicCube

3、切后台

3.1 支持后台播放

如果开发者希望 App 退至后台依然支持音频播放、录制,需要先在项目中开启后台模式,并指定模式为 Audio,AirPlay,and Picture in Picture,如图所示:
在这里插入图片描述
设置后,Xcode 会自动在项目的 Info.plist 中添加对应条目 Required background modes: App plays audio or streams audio/video using AirPlay。

开启此选项,当应用退至后台,只要有音频播放、录制行为,就可以一直运行。运行时,状态栏会变成红色,指示用户当前有麦克风设备在后台运行。

3.2 停止后台播放

开发者开启后台模式,如果在某些场景下需要在后台停止音频播放或录制,依然可以使用 pauseModule resumeModule 实现。

请注意,iOS 系统不支持 App 在后台播放或采集视频画面(注意视频声音属于声音内容,支持后台播放),因此视频画面无需额外暂停或恢复。

对于 App 切换前后台行为的监听,有两种常用方式:

1.在 AppDelegate.m 对应的系统方法中处理。详见 Apple 官方指南:The App Life Cycle

2.注册通知监听状态。示例代码如下:

// 监听 App 切后台
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(appDidEnterBackground:)
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:nil];

// 监听 App 从后台切前台
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(appWillEnterForeground:)
                                             name:UIApplicationWillEnterForegroundNotification
                                           object:nil];

在上述方法中,停止后台播放音频的步骤为:

1.App 切后台,调用 pauseModule 暂停音频模块。

2.App 切换回前台,调用 resumeModule 恢复音频模块。

猜你喜欢

转载自blog.csdn.net/sinat_20146421/article/details/84112047