Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play/Pause callback not getting called when using MPRemoteCommandCenter

I am building a music player app, and everything is working fine. I have been using the system music player so far, but now want to switch over to use an application music player instead, and that's where I'm running into problems - for the life of me I can't figure out how to get my play/pause callback to be called from the iOS control center. Here's the code I'm using in my main view controller:

override func viewDidLoad() {
    super.viewDidLoad()

    self.musicPlayer = MPMusicPlayerController.applicationMusicPlayer()

    self.registerForMediaPlayerNotifications()
    UIApplication.sharedApplication().beginReceivingRemoteControlEvents()

    let commandCenter = MPRemoteCommandCenter.sharedCommandCenter()

    commandCenter.previousTrackCommand.enabled = false
    commandCenter.previousTrackCommand.addTarget(self, action: "previousTrack")
    commandCenter.nextTrackCommand.enabled = false
    commandCenter.nextTrackCommand.addTarget(self, action: "nextTrack")
    commandCenter.togglePlayPauseCommand.enabled = true
    commandCenter.togglePlayPauseCommand.addTarget(self, action: "playOrPauseMusic")
    commandCenter.pauseCommand.addTarget(self, action: "playOrPauseMusic")
    commandCenter.pauseCommand.enabled = true
    commandCenter.playCommand.addTarget(self, action: "playOrPauseMusic")
    commandCenter.playCommand.enabled = true

    [...]
}


func previousTrack() {
}

func nextTrack() {
}

func playOrPauseMusic() {
   print("playOrPause")
}
like image 222
dflachbart Avatar asked Nov 08 '22 21:11

dflachbart


2 Answers

I had this same issue and noticed that the callback for togglePlayPauseCommand wasn't getting called, but previousTrackCommand was. So after some experimentation I got this working by removing togglePlayPauseCommand and instead indiviudally implementing the inline callbacks for playCommand and pauseCommand - please note that using custom selectors weren't working, they had to be the inline callbacks.

let commandCenter = MPRemoteCommandCenter.shared()

commandCenter.playCommand.addTarget { (commandEvent) -> MPRemoteCommandHandlerStatus in
    moviePlayer.prepareToPlay()
    moviePlayer.play()
    return MPRemoteCommandHandlerStatus.success
}

commandCenter.pauseCommand.addTarget { (commandEvent) -> MPRemoteCommandHandlerStatus in
    moviePlayer.pause()
    return MPRemoteCommandHandlerStatus.success
}
like image 77
Anconia Avatar answered Nov 15 '22 07:11

Anconia


Try adding Required background modes to the Info.plist like this:

Info.plist screenshot

like image 45
satoshin Avatar answered Nov 15 '22 05:11

satoshin