Detect headset button click on iPhone SDK

后端 未结 3 930
面向向阳花
面向向阳花 2020-12-08 17:45

Is there a way to detect the headset\'s play/pause button click?

I managed to detect the volume buttons clicks using:

AudioSessionAddPropertyListener         


        
3条回答
  •  渐次进展
    2020-12-08 18:11

    Tried all above but sadly now none seems to work. Then I took a peek at beginReceivingRemoteControlEvents and found this

    In iOS 7.1 and later, use the shared MPRemoteCommandCenter object to register for remote control events. You do not need to call this method when using the shared command center object.

    Then checked out MPRemoteCommandCenter and finally ended up in MPRemoteCommand documentation page.

    Good thing is there is this example:

    let commandCenter = MPRemoteCommandCenter.shared()
    commandCenter.playCommand.addTarget(handler: { (event) in    
    
        // Begin playing the current track    
        self.myMusicPlayer.play()
        return MPRemoteCommandHandlerStatus.success
    })
    

    Now if we want to read middle button we can do:

    MPRemoteCommandCenter.shared().togglePlayPauseCommand.addTarget { (event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus in
    
     // middle button (toggle/pause) is clicked
     print("event:", event.command)
    
     return .success
    }
    

    This works and I managed to get the headphone's middle button detected.

    Note: I noticed there is different behaviour that depends on where we put such code above. That is when I put in View Controller the reported events are identical and when I put it in AppDelegate's didFinishLaunching the reported events are different. Either way the event is detected.

提交回复
热议问题