Build Command-Center like Media Controls

201 views Asked by At

I want to build a control in my app that can play/pause and skip the sound that is played in the background. This should behave the same way as the media control does for all different media sources at the control center. Screenshot

I played around with various options. AVAudioSession, MPRemoteCommandCenter and also acquiring some Bluetooth profiles, as headphones can play/pause background music as well. Unfortunately nothing was able to play/pause the background music.

Does anyone have an idea how to make this behavior happen.

1

There are 1 answers

1
Hach3m On

If you are trying to make your audio app use control center (like spotify does) you need to use the MPNowPlayingInfoCenter to set the now playing item data (like:title, rate, duration, elapsedTime,...) it will be something like that:

MPNowPlayingInfoCenter.default().nowPlayingInfo = [
        MPMediaItemPropertyTitle: title,
        MPMediaItemPropertyArtist: artist,
        MPNowPlayingInfoPropertyElapsedPlaybackTime: position,
        MPMediaItemPropertyPlaybackDuration: duration,
        MPNowPlayingInfoPropertyPlaybackRate: rate,
    ]

this will set the data of the played audio item in the media control center now in order to be able to use the controls button need to use the MPRemoteCommandCenter and set the target for each command you want to use for example for play/pause actions it can be done like that:

    MPRemoteCommandCenter.shared().playCommand.addTarget(handler: playActionHandler)
    MPRemoteCommandCenter.shared().pauseCommand.addTarget(handler: pauseActionHandler)

once all of this is done you will need to call the method bellow in order for your app to be able to receive the remote events and execute the needed action

        UIApplication.shared.beginReceivingRemoteControlEvents()