NotificationCenter.default.addObserver(self, selector: #selector(audioRouteChangeListenerCallback(notification:)), name: AVAudioSession.routeChangeNotification, object: AVAudioSession.sharedInstance())
@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 }
原文:https://www.cnblogs.com/xjf125/p/12655915.html