Well, actually setting the rate to 0, and resetting the time to its actual value when I pause and play did the trick.
MPNowPlayingInfoCenter - elapsed time keeps counting when audio paused
-
29-08-2022 - |
Question
I'm currently trying to figure out how to specify the elapsed time in the MPNowPlayingInfoCenter
, on iOS.
When I start playing, I set the elapsed time to 0 and the playback rate to 1. This works fine.
Then I pause the audio. This is correctly detected by the MPNowPlayingInfoCenter, and it pauses the elapsed time on the interfaces.
It's only when I resume playing that things go wrong: the time is displayed as if it kept playing while paused. Example:
1. Start playback
2. Let it play for 10 seconds
3. Pause for 5 seconds
4. Resume playback
At this point, the actual time in the track is 10 seconds. Yet the info center displays 15.
I tried to set the playback rate to 0 while paused, but this results in a weird behavior: the displayed time randomly changes to a lower value.
Also, I don't really have an opportunity to update the elapsed time before resuming the song, as I only get a chance to do so after I receive the play
event.
tl;dr: How to handle pauses in the MPNowPlayingInfoCenter and its time feature?
Solution
OTHER TIPS
Well, I have put a selector for MPMoviePlayerPlaybackStateDidChangeNotification notification. It is called whenever movie is play, paused, slide up/down infocenter (control center). Or even if the movie is streaming and it do pause/play on receive response.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(movieStateChange)
name:MPMoviePlayerPlaybackStateDidChangeNotification
object:nil];
And I do
- (void)movieStateChange{
[self updateControlCenter];
}
And thats my updateControlCenter, it takes already initlaized playing info and update the MPNowPlayingInfoPropertyElapsedPlaybackTime
key.
- (void)updateControlCenter{
NSMutableDictionary *nowPlayingInfo = [center.nowPlayingInfo mutableCopy];
[nowPlayingInfo setObject:[NSNumber numberWithDouble:self.player.currentPlaybackTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
center.nowPlayingInfo = nowPlayingInfo;
}
Good luck!
I had this problem and solved it by updating the elapsed time every time you play a track. So your 'play' button should update the information
Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
if (playingInfoCenter) {
NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
[songInfo setObject:currentTrack.trackTitle forKey:MPMediaItemPropertyTitle];
[songInfo setObject:currentTrack.artist forKey:MPMediaItemPropertyArtist];
[songInfo setObject:currentTrack.albumTitle forKey:MPMediaItemPropertyAlbumTitle];
[songInfo setObject:currentTrack.trackLength forKey:MPMediaItemPropertyPlaybackDuration];
[songInfo setObject:currentTime forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];}