Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect headset button click on iPhone SDK

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

I managed to detect the volume buttons clicks using:

AudioSessionAddPropertyListener( kAudioSessionProperty_CurrentHardwareOutputVolume , audioVolumeChangeListenerCallback, self );

But I can't find an AudioSessionProperty for the center button. What's the way to do that?

like image 869
MCO Avatar asked Sep 15 '11 09:09

MCO


1 Answers

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.

like image 123
Fitsyu Avatar answered Nov 03 '22 16:11

Fitsyu