- 1、监听音频打断事件
NotificationCenter.default.addObserver(self, selector: #selector(audioStart(_:)), name: NSNotification.Name.AVAudioSessionInterruption, object: nil)
- 2、在通知方法中处理音频中断事件
AVAudioSessionInterruptionType
有两种类型:began
和ended
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 收到音频中断结束通知")
//恢复音频
}
}