Headphones plugin/out detection in Swift

前端 未结 3 1539
轻奢々
轻奢々 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:35

    This article worked for me. There is also a GitHub repo with solution. If you don't want to read, here is my code:

    Put this in your INIT method:

        self.session = AVAudioSession.sharedInstance()
        let currentRoute = self.session.currentRoute
        if currentRoute.outputs.count != 0 {
            for description in currentRoute.outputs {
                if description.portType == AVAudioSessionPortHeadphones {
                    print("headphone plugged in")
                } else {
                    print("headphone pulled out")
                }
            }
        } else {
            print("requires connection to device")
        }
    
        NSNotificationCenter.defaultCenter().addObserver(
            self,
            selector: #selector(YOUR_VIEW_CONTROLLER_OR_VIEW.audioRouteChangeListener(_:)),
            name: AVAudioSessionRouteChangeNotification,
            object: nil)
    

    And put this anywhere in your class:

     dynamic private func audioRouteChangeListener(notification:NSNotification) {
        let audioRouteChangeReason = notification.userInfo![AVAudioSessionRouteChangeReasonKey] as! UInt
    
        switch audioRouteChangeReason {
        case AVAudioSessionRouteChangeReason.NewDeviceAvailable.rawValue:
            print("headphone plugged in")
        case AVAudioSessionRouteChangeReason.OldDeviceUnavailable.rawValue:
            print("headphone pulled out")
        default:
            break
        }
    }
    

    Take care!

提交回复
热议问题