Headphones plugin/out detection in Swift

前端 未结 3 1473
轻奢々
轻奢々 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: ()
                }
    
            }
    
    0 讨论(0)
  • 2020-12-29 17:26

    You can track the route changes by observing AVAudioSessionRouteChangeNotification notification.

    //Observe for route changing notification
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(handleRouteChange:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
    
       -(void)handleRouteChange:(NSNotification *)notif
        {
           NSDictionary *dict = notif.userInfo;
           AVAudioSessionRouteDescription *routeDesc = dict[AVAudioSessionRouteChangePreviousRouteKey];
           AVAudioSessionPortDescription *prevPort = [routeDesc.outputs objectAtIndex:0];
           if ([prevPort.portType isEqualToString:AVAudioSessionPortHeadphones]) {
                //Head phone removed
              }
         }
    
    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题