【Swift】監聽耳機插入拔出的通知


  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
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM