1、注册通知
NotificationCenter.default.addObserver(self, selector: #selector(audioRouteChangeListenerCallback(notification:)), name: AVAudioSession.routeChangeNotification, object: AVAudioSession.sharedInstance())
2、处理接收的通知
@objc func audioRouteChangeListenerCallback(notification:NSNotification) {
guard let userInfo = notification.userInfo,
let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
let reason = AVAudioSession.RouteChangeReason(rawValue:reasonValue) else {
return
}
switch reason {
case .newDeviceAvailable:
//插入耳机时关闭扬声器播放
self.agoraKit?.setEnableSpeakerphone(false)
case .oldDeviceUnavailable:
//播出耳机时,开启扬声器播放
self.agoraKit?.setEnableSpeakerphone(true)
default: ()
}
}
附:是否插入耳机
func hasHeadset() -> Bool {
let audioSession = AVAudioSession.sharedInstance()
let currentRoute = audioSession.currentRoute
for output in currentRoute.outputs {
if output.portType == AVAudioSession.Port.headphones {
return true
}
}
return false
}