You need to enable JavaScript to run this app. Swift开发:如何获取AVAudioSession音频中断的触发原因
优惠活动
大模型
产品
解决方案
定价
更多

Swift开发:如何获取AVAudioSession音频中断的触发原因

可直接复用的中断原因获取方案

你需要的中断原因信息不需要额外接入新的API或代理方法,直接在你当前已经监听的AVAudioSessionInterruptionNotification通知的userInfo字典中就可以获取,完全适配你现有的中断处理逻辑,不需要大改现有代码结构。

系统提供的中断原因枚举匹配

从iOS 14开始,苹果在中断通知的userInfo中新增了专属原因键AVAudioSessionInterruptionReasonKey,返回结构化的中断原因枚举,和你需要识别的场景对应关系如下:

  • AVAudioSession.InterruptionReason.default:对应第三方App激活自身音频会话抢占焦点的场景,即你提到的Gaana、Wynk等其他音乐类App抢占播放的情况
  • AVAudioSession.InterruptionReason.builtInAudioInUse:对应设备内置音频通道被高优先级任务占用的场景,包括运营商来电、短信触发的系统提示音通道占用、系统自带录音功能运行时的中断
  • AVAudioSession.InterruptionReason.routeDisconnected:对应耳机拔出、蓝牙音频设备断开连接触发的中断场景
  • AVAudioSession.InterruptionReason.appWasSuspended:对应当前App被系统挂起触发的中断,不属于外部因素抢占
注意事项与兼容逻辑
  • 上述原因键仅在中断通知的InterruptionType为.began(中断开始)的分支下有有效值,中断结束的分支中无法获取有效原因,需要在中断开始的处理逻辑中完成取值
  • 对于iOS 14以下的低版本系统,不存在结构化的原因枚举,可以结合运行时状态做场景推断:中断发生时如果App处于前台运行状态,可判定为外部应用抢占;如果中断前后伴随运营商来电状态变更,可判定为通话触发的中断;如果中断伴随音频路由变化通知,可判定为设备断开类中断
  • 现有中断通知的注册、暂停/恢复播放的核心逻辑完全不需要调整,仅需在现有代码中插入原因提取的埋点逻辑即可
实现示例代码

在你现有的中断通知处理逻辑中插入原因提取代码即可,参考示例:

NotificationCenter.default.addObserver(forName: AVAudioSession.interruptionNotification, object: nil, queue: .main) { notification in
    guard let userInfo = notification.userInfo,
          let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
          let interruptionType = AVAudioSession.InterruptionType(rawValue: typeValue) else {
        return
    }
    
    switch interruptionType {
    case .began:
        // 原有暂停播放的逻辑
        if #available(iOS 14.0, *) {
            if let reasonValue = userInfo[AVAudioSessionInterruptionReasonKey] as? UInt,
               let interruptionReason = AVAudioSession.InterruptionReason(rawValue: reasonValue) {
                // 将提取到的原因传入数据分析埋点
                switch interruptionReason {
                case .default:
                    print("中断场景:其他音乐类App抢占")
                case .builtInAudioInUse:
                    print("中断场景:通话/系统高优先级音频任务占用")
                case .routeDisconnected:
                    print("中断场景:音频路由断开")
                case .appWasSuspended:
                    print("中断场景:App被系统挂起")
                @unknown default:
                    break
                }
            }
        } else {
            // 低版本系统的原因推断埋点逻辑
        }
    case .ended:
        // 原有根据可恢复选项判断是否续播的逻辑
    @unknown default:
        break
    }
}

内容的提问来源于stack exchange,提问作者DJ1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.10 21:45:02