首页 > 编程语言 > 详细

【Swift】监听耳机插入拔出的通知

时间:2020-04-07 21:28:36      阅读:99      评论:0      收藏:0      [点我收藏+]

  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
    }

 

【Swift】监听耳机插入拔出的通知

原文:https://www.cnblogs.com/xjf125/p/12655915.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!