Best ipod questions in June 2011

Control iPod from another app?

9 votes

I took a look at Apple's AddMusic sample code, but that's not quite what I want. I'm trying to find a way to start/stop music playing in the iPod app, not controlling what's contained in my app's sandbox.

Something like this...

 ____________
|            |
| |<  ||  >| |    skip back, play/pause, skip forward
|            |
|  XXXXXXXX  |    album art
|  XXXXXXXX  |
|  XXXXXXXX  |
|  XXXXXXXX  |
|            |
|____________|

Of course the app is more complex than this, but for now, I want to focus on assuming direct control.
+1 virtual cookie if you get the reference without using Google.

If this definitely isn't possible, I can rework AddMusic, but I'd rather not. Too messy.


— Artwork loading error moved to a new question.

— Text-to-Speech implementation moved to a new question.

— Progress bar fills to 100% as soon as the song starts. Working on a fix. (Failing pretty badly right now...)

The MediaPlayer framework is what you are looking for. There is a useful guide which also contains a link to the MediaPlayer API overview.

Specifically, you're looking for MPMusicPlayerController. Your app can control either a dedicated app media player or the iPod media player which appears to be what you want.

A simple example would be something like (header omitted):

@implementation MyPlaybackController

- (id)initWithNibName:(NSString *)nibName bundle:(id)bundleOrNil 
{
  if ((self = [super initWithNibName:nibName bundle:bundleOrNil])) {
    self.musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
  }  
  return self;
}

- (IBAction)skipForward:(id)sender
{
  [self.musicPlayer skipToNextItem];
}

- (IBAction)skipBack:(id)sender
{
  [self.musicPlayer skipToPreviousItem];
}

- (IBAction)togglePlayback:(id)sender
{
  if (self.musicPlayer.playbackState == MPMusicPlaybackStatePlaying) {
    [self.musicPlayer pause];
  } else {
    [self.musicPlayer play];
  }
}

@end

Do take time to read the documentations and take note of the caveats mentioned with regards to Home Sharing. You'll also want to register for notifications in changes to the player state that can occur from outside your control.