iOS听筒和外放切换 发表于 2017-11-24 | 分类于 ios iOS听筒和外放切换 本文语法为Swift4 代码主要涉及到距离传感器的调用 1234567891011121314151617181920212223242526func addProximityMonitoring(){ UIDevice.current.isProximityMonitoringEnabled = true; if(UIDevice.current.isProximityMonitoringEnabled){ NotificationCenter.default.addObserver(self, selector: #selector(ChatViewController.sensorStateChange(_:)), name: NSNotification.Name.UIDeviceProximityStateDidChange, object: nil); }} func removeProximityMonitoring(){ UIDevice.current.isProximityMonitoringEnabled = true; if(UIDevice.current.isProximityMonitoringEnabled){ UIDevice.current.isProximityMonitoringEnabled = false; NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceProximityStateDidChange, object: nil); }} @objc func sensorStateChange(_ notification:NotificationCenter){ do{ if(UIDevice.current.proximityState){ try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord); }else{ try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback); } }catch{ }}