实时语音
  • iOS : Objective-C
  • Android
  • Windows
  • 概述
  • 限制说明
  • SDK 下载
  • 快速开始
  • 进阶功能
  • API 文档
  • 常见错误码
  • 语音通话
  • 语音直播
  • 游戏语音
  • 文档中心
  • 实时语音
  • 进阶功能
  • 打断事件处理

打断事件处理

更新时间:2021-09-30 11:25

1 简介

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

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

ZegoAudioRoomApi.h

/**
 暂停模块

 @attention 用于需要暂停指定模块的场合,例如来电时暂定音频模块
 @note 暂停指定模块后,注意在合适时机下恢复模块
 */
- (void)pauseAudioModule;
ZegoAudioRoomApi.h

/**
 恢复模块

 @attention 用于需要恢复指定模块的场合,例如来电结束后恢复音频模块
 @note 暂停指定模块后,注意在合适时机下恢复模块
 */
- (void)resumeAudioModule;

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

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] pauseAudioModule];
    }
    else if(AVAudioSessionInterruptionTypeEnded == [notification.userInfo[AVAudioSessionInterruptionTypeKey] intValue])
    {
        // 恢复音频设备
        [[ZegoDemoHelper api] resumeAudioModule];
    }
}

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

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

Apple 官方指导详见: Background Execution

3.2 停止后台播放

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

对于 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 切后台,调用 pauseAudioModule 暂停音频模块。
  2. App 切换回前台,调用 resumeAudioModule 恢复音频模块。
本篇目录