AVAudioSessionInterruption的AudioKit处理

cax*_*xix 5 iphone interruption ios avaudiosession audiokit

接到电话或刚打完电话后,启用了后台播放的AudioKit应用程序将永久静音,我不确定如何处理。重新启动声音输出的唯一方法是杀死并重新启动应用程序。其他中断(例如启用和使用Siri)可以毫无障碍地进行,并且在活动期间,应用的声音会回落。

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

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

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

小智 3

这将取决于您的应用程序如何处理此问题。至少,当中断完成时,您需要执行 Audiokit.stop() ,然后执行 Audiokit.start() 。

您需要通过以下方式注册通知:

NotificationCenter.default.addObserver(self,
                                           selector: #selector(handleInterruption),
                                           name: .AVAudioSessionInterruption,
                                           object: nil)
Run Code Online (Sandbox Code Playgroud)

然后用这样的方法处理它:

@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
}
Run Code Online (Sandbox Code Playgroud)