Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MPRemoteCommandCenter not generating remote control events MPMusicPlayerController.applicationMusicPlayer()

I'm using MPRemoteCommandCenter and MPMusicPlayerController.applicationMusicPlayer on the iPhone.

I'm trying to receive remote control events when the user is playing music and double taps on the headphone button.

If I use AVAudioPlayer, the remote commands are received perfectly.

However, if I use MPMusicPlayerController with any of its players (systemMusicPlayer, applicationMusicPlayer, or applicationQueuePlayer) the the commands do not get received. They appear to get gobbled up. For example when I double tap the remote, the music will toggle between play and stop. Instead, I need the remote events sent to my app.

Below is a sample app with my code. In the info.plist I've specified the required background mode for an app that plays audio (although its not necessary).

import UIKit
import MediaPlayer

class ViewController: UIViewController {
    var mpPlayer:MPMusicPlayerController!

    func remoteHandler() {
        print("success")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        mpPlayer = MPMusicPlayerController.applicationMusicPlayer()
        //mpPlayer = MPMusicPlayerController.systemMusicPlayer()
        assert(mpPlayer != nil)

        let cc = MPRemoteCommandCenter.shared()
        print("cc = \(cc)")

        cc.nextTrackCommand.isEnabled = true
        cc.nextTrackCommand.addTarget(self, action: #selector(ViewController.remoteHandler))
        cc.previousTrackCommand.isEnabled = true
        cc.previousTrackCommand.addTarget(self, action: #selector(ViewController.remoteHandler))
        cc.playCommand.isEnabled = true
        cc.playCommand.addTarget(self, action: #selector(ViewController.remoteHandler))

        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            print("AVAudioSession successfully set AVAudioSessionCategoryPlayback")
        } catch let error as NSError {
            print("AVAudioSession setCategory error: \(error.localizedDescription)")
        }
        mpPlayer.setQueueWithStoreIDs(["270139033"]) // requires iOS 10.3
        mpPlayer.play()

    }
}

Output is:

cc = 0x123e086c0

AVAudioSession successfully set AVAudioSessionCategoryPlayback

remoteHandler is never called.
like image 225
salferrari Avatar asked Nov 07 '22 19:11

salferrari


1 Answers

From the Apple Developer web site.

When you use either the system or application player, you do not get event notifications. Those players automatically handle events.

So there is no way to receive remote control events if you use MPMusicPlayerController. Looking forward to see this feature! Right now MPMusicPlayerController is the only way to play Apple Music songs.

like image 61
Grigory Bochkarev Avatar answered Nov 15 '22 11:11

Grigory Bochkarev