MPMusicPlayerController applicationMusicPlayer - Resume when application launches
-
06-07-2021 - |
Question
The MPMusicPlayerController applicationMusicPlayer
runs independent of the iPod (or Music) app, which is what I want. It stops playing when the application goes into the background which is again what I want.
However, I would like it to resume playing when the application resumes. Currently I do this by calling the play method again, however this causes the audio to start from the beginning. Is there a way I can actually resume playing from where the audio left off? I can't seem to find anything about it.
Solution
Inside the App Delegate's applicationWillResignActive:
method, read the musicPlayer.currentPlaybackTime
property (declared in the MPMediaPlayback protocol) and store that value somewhere. You could set up a property such as:
@property (assign, nonatomic) NSTimeInterval playbackTime;
and assign it with:
- (void)applicationWillResignActive:(UIApplication *)application
{
MPMusicPlayerController *myPlayer =
[MPMusicPlayerController applicationMusicPlayer];
self.playbackTime = myPlayer.currentPlaybackTime;
[myPlayer pause];
}
When the app is about to become active again, the App Delegate's applicationDidBecomeActive:
method will be called. Inside that method, set the currentPlaybackTime property.
- (void)applicationDidBecomeActive:(UIApplication *)application
{
MPMusicPlayerController *myPlayer =
[MPMusicPlayerController applicationMusicPlayer];
myPlayer.currentPlaybackTime = self.playbackTime;
[myPlayer play];
}