Akash Malhotra
Akash Malhotra

Reputation: 1106

MPMusicPlayerController pause while in background and resume when app enters foreground

I have implemented MPMusicPlayerController to play music from library. When app enters background, i pause it and when it comes back to foreground, i want it to resume. It pauses fine but begins from the start. Heres the code...

AppDelegate.m

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [self.appMusicPlayer pause];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [self.appMusicPlayer play];
}

MainViewController.m

- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection 
{
    [self dismissModalViewControllerAnimated: YES];
   appdelegate.selectedSongCollection=mediaItemCollection; 
    appdelegate.appMusicPlayer = [MPMusicPlayerController applicationMusicPlayer];

    [appdelegate.appMusicPlayer setQueueWithItemCollection:appdelegate.selectedSongCollection];
    [appdelegate.appMusicPlayer play];
    [btnStop setHidden:NO];
    [btnMusic setHidden:YES];
}

- (void) mediaPickerDidCancel: (MPMediaPickerController *) mediaPicker 
{   
    [self dismissModalViewControllerAnimated: YES]; 
}

Any ideas on how to resume it when app enters foreground?

Upvotes: 2

Views: 1268

Answers (1)

jmstone617
jmstone617

Reputation: 5707

I would look into the track's currentPlaybackTime. MPMusicPlayerController has a currentPlaybackTime property. When the app is going to enter the background, simply save this value (as a property should work just fine), and in WillEnterForeground, use the same property's value to set the currentPlaybackTime when you resume.

Upvotes: 2

Related Questions