0
votes

I am writing a music playing app which performs a task between each song. I need to do this even when the app is in the background, so I need to know when a song has completed. At the moment I am using AVPlayer which sends notifications even when the app is in the background, but is unable to play songs from the user's iCloud. MPMediaPlayerController can play iCloud songs but doesn't send notifications when the app is in the background (which is essential to my app).

So, does anyone know either

  1. Any clever ways of having AVPlayer play iCloud songs, or
  2. Having my app recognise when a song playing via MPMusicPlayerController has completed when the app is in the background?
2
Did you ever solve this for your app? - newenglander

2 Answers

2
votes

Have you tried using NSNotification Center and one of these two observers? MPMusicPlayerControllerPlaybackStateDidChangeNotification or MPMusicPlayerControllerNowPlayingItemDidChangeNotification.

Also, you need to use beginGeneratingPlaybackNotifications() on your instance of MPMusicPlayerController.applicationMusicPlayer() or MPMusicPlayerController.systemMusicPlayer()

1
votes

To build on @Kim's answer. You can use the NSNotificationCenter and add ObserverEvents. I use the MPMusicPlayerController class for my application, and I've registered the application to use the NSNotificationCenter properties so I can call certain methods during differing events.

For instance, while using the SystemMusicPlayer property if you exit and terminate the application process, the music keeps playing. If the user wanted to stop the music when they exityou could call this:

-(void) registerMediaPlayerNotifications {
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

    [notificationCenter addObserver:self
                           selector:@selector(stopMusicWhenApplicationQuits)
                               name:UIApplicationWillTerminateNotification
                             object:[UIApplication sharedApplication]];
    [musicPlayer beginGeneratingPlaybackNotifications];
}

Where you see the @selector that is the method that will be fired when the application receives the UIApplicationWillTerminateNotification event. Which in the musicPlayer you can say

[self.musicPlayer stop];

So for the question you have, you can still use the MediaPlayer framework, use the MPMusicPlayerController class and call various methods during different application runtime stages using the NSNotificationCenter properties.

Hope this helps, let me know if you have any further questions.