首页 > 解决方案 > AudioKit 处理 AVAudioSessionInterruption

问题描述

在接到电话或只是让电话响起后,我们启用了后台播放的 AudioKit 应用程序会永久静音,我不知道如何处理。重新启动声音输出的唯一方法是杀死并重新启动应用程序。其他中断,如启用和使用 Siri 工作顺利,应用程序的声音在活动期间被闪避。

通常,应用程序可以注册自己以接收通知(例如NSNotification.Name.AVAudioSessionInterruption)以检测AVAudioSession中断,但是如何检索AVSession通常传递到通知中的对象?

NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.sessionInterrupted(_:)),
                                               name: NSNotification.Name.AVAudioSessionInterruption,
                                               object: MISSING_AK_AVAUDIOSESSION_REF)

此外,如果能够成功实现音频中断通知,那么 AudioKit 会发生什么?它不是为“重新启动”或暂停而设计的。任何帮助将非常感激。

标签: iosiphoneavaudiosessionaudiokitinterruption

解决方案


这将取决于您的应用程序如何处理它。至少,您需要在中断完成时执行 Audiokit.stop() 和 Audiokit.start() 。

您需要使用以下内容注册通知:

NotificationCenter.default.addObserver(self,
                                           selector: #selector(handleInterruption),
                                           name: .AVAudioSessionInterruption,
                                           object: nil)

然后用这样的东西处理它:

@objc internal func handleInterruption(_ notification: Notification) {
    guard let info = notification.userInfo,
        let typeValue = info[AVAudioSessionInterruptionTypeKey] as? UInt,
        let type = AVAudioSessionInterruptionType(rawValue: typeValue) else {
            return
    }
    //...handle each type here
}

推荐阅读