I'm working on an app that will play sound files. If I open apple music app, the slider let me moving between the song where I am.
Other apps like spotify or overcast does not allow this behaviour.
Until now, I have been able to change all parameters of the control center with that exception. Is there any way of making this slider useful?
I'm using something like the following code:
MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
NSArray *commands = @[commandCenter.playCommand, commandCenter.pauseCommand, commandCenter.nextTrackCommand, commandCenter.previousTrackCommand, commandCenter.bookmarkCommand, commandCenter.changePlaybackPositionCommand, commandCenter.changePlaybackRateCommand, commandCenter.dislikeCommand, commandCenter.enableLanguageOptionCommand, commandCenter.likeCommand, commandCenter.ratingCommand, commandCenter.seekBackwardCommand, commandCenter.seekForwardCommand, commandCenter.skipBackwardCommand, commandCenter.skipForwardCommand, commandCenter.stopCommand, commandCenter.togglePlayPauseCommand];
for (MPRemoteCommand *command in commands) {
[command removeTarget:nil];
[command setEnabled:NO];
}
[commandCenter.playCommand addTarget:self action:@selector(playTrack)];
[commandCenter.pauseCommand addTarget:self action:@selector(pauseTrack)];
[commandCenter.playCommand setEnabled:YES];
[commandCenter.pauseCommand setEnabled:YES];
The New Way for iOS 12+ and Swift 4+
Following is an improved way of handling scrubbing in Remote Play Center:
// Handle remote events
func setupRemoteTransportControls() {
let commandCenter = MPRemoteCommandCenter.shared()
// Scrubber
commandCenter.changePlaybackPositionCommand.addTarget { [weak self](remoteEvent) -> MPRemoteCommandHandlerStatus in
guard let self = self else {return .commandFailed}
if let player = self.player {
let playerRate = player.rate
if let event = remoteEvent as? MPChangePlaybackPositionCommandEvent {
player.seek(to: CMTime(seconds: event.positionTime, preferredTimescale: CMTimeScale(1000)), completionHandler: { [weak self](success) in
guard let self = self else {return}
if success {
self.player?.rate = playerRate
}
})
return .success
}
}
return .commandFailed
}
// Register to receive events
UIApplication.shared.beginReceivingRemoteControlEvents()
}
As of 2020 with Swift 5, if we only use commandCenter.changePlaybackPositionCommand
it won't work, we also need to set metadata with MPMediaItemPropertyPlaybackDuration
for the player then we can use the slider.
Check this article from Apple: https://developer.apple.com/documentation/avfoundation/media_assets_playback_and_editing/creating_a_basic_video_player_ios_and_tvos/controlling_background_audio
Look at the section: Provide Display Metadata
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With