• 1、监听音频打断事件
NotificationCenter.default.addObserver(self, selector: #selector(audioStart(_:)), name:  NSNotification.Name.AVAudioSessionInterruption, object: nil)
  • 2、在通知方法中处理音频中断事件
    AVAudioSessionInterruptionType有两种类型:beganended
public enum InterruptionType : UInt {

        case began = 1

        case ended = 0
    }
  • began表示收到中断事件开始的通知
  • ended表示收到中断事件结束的通知
@objc private func audioStart(_ note: Notification){
        print("addInterruptionSession \(note) \(note.userInfo![AVAudioSessionInterruptionTypeKey])")
        
        if AVAudioSessionInterruptionType.began.rawValue == note.userInfo![AVAudioSessionInterruptionTypeKey] as? UInt{
            print("addInterruptionSession 收到音频中断开始通知")
            //暂停音频

        } else if AVAudioSessionInterruptionType.ended.rawValue == note.userInfo![AVAudioSessionInterruptionTypeKey]as? UInt{
            print("addInterruptionSession 收到音频中断结束通知")
            //恢复音频
        }
    }