0

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 Answers1

0

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()
Hach3m
  • 71
  • 6
  • Thanks for the reply. Unfortunately my app does not play any sounds. It is more of like a dashboard. Where different information are shown at a glance and you also have some controls. I wanted to add controls for the playback media as well. That's what caused my question. – Jonas Vienhues Dec 24 '21 at 11:44