views:

542

answers:

1

Hi,

I'm working on an iPhone iOS4 application that incorporates playing music from the user's iPod library. I also want to keep track of what songs have been played and be able to change the song randomly, even while in the background. So I set the music player using:

[self setMusicPlayer: [MPMusicPlayerController iPodMusicPlayer]];

Now, I want this application to continue to run and play music in the background, so I have set:

Required background modes: App plays audio

The problem I'm having is that my application loses control when it is moved into the background (when applicationDidEnterBackground is called, ie. on app switches). Since I'm using the iPodMusicPlayer the music continues to play but my app does not have control and therefore can't track or change the song.

Now, the Apple documentation states that your application should continue to execute in the background using this required background modes tag, but mine does not. Is it because I'm using MPMusicPlayer? Is there any way to get around it? Any ideas?

PS. I'm also trying to get the remote locked and multitasking iPod controllers to work with my application. I'm using the code below, but remoteControlReceivedWithEvent never gets called! Does it work with MPMusicPlayer? I've only seen it with AVAudioPlayer.

- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    NSLog(@"remoteControlReceivedWithEvent");
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlTogglePlayPause:
            NSLog(@"Play Pause");
            break;
        case UIEventSubtypeRemoteControlNextTrack:
            NSLog(@"Next");
            break;
        default:
            break;
    }
}

- (BOOL)canBecomeFirstResponder {
    NSLog(@"canBecomeFirstResponder");
    return YES;
 }

- (void) viewWillAppear:(BOOL)animated{
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}
+1  A: 

You are correct. Your iPhone app will not run in the background while using MPMusicPlayerController. This will also prevent you from receiving remote control events.

If you want to play audio from the iPod library and have your app continue running in the background, you must use the lower-level AVPlayer class.

David Patierno