Headphones plugin/out detection in Swift

前端 未结 3 1524
轻奢々
轻奢々 2020-12-29 16:50

im working on an iphone app for iOS 8.1 that works with core audio to generate frequencies and adjust intensities. In the view controller that i generate the frequencies i n

3条回答
  •  暖寄归人
    2020-12-29 17:25

    In Swift 4

        func activateHeadPhonesStatus(){
         NotificationCenter.default.addObserver(self, selector: #selector(audioRouteChangeListener(_:)), name: AVAudioSession.routeChangeNotification, object: nil)
        }
    
        @objc func audioRouteChangeListener(_ notification:Notification) {
                guard let userInfo = notification.userInfo,
                    let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt,
                    let reason = AVAudioSession.RouteChangeReason(rawValue:reasonValue) else {
                        return
                }
                switch reason {
                case .newDeviceAvailable:
                    let session = AVAudioSession.sharedInstance()
                    for output in session.currentRoute.outputs where output.portType == AVAudioSession.Port.headphones {
                        headphonesConnected = true
                        print("headphone plugged in")
                        break
                    }
                case .oldDeviceUnavailable:
                    if let previousRoute =
                        userInfo[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription {
                        for output in previousRoute.outputs where output.portType == AVAudioSession.Port.headphones {
                            headphonesConnected = false
                            print("headphone pulled out")
                            break
                        }
                    }
                default: ()
                }
    
            }
    

提交回复
热议问题