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.
Bonus points to anyone who gets the reference without cheating.
— 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. This code works:
// your must register for notifications to use them
- (void)handleNowPlayingItemChanged:(id)notification {
…
// this is what I forgot to do
NSNumber *duration = [item valueForProperty:MPMediaItemPropertyPlaybackDuration];
float totalTime = [duration floatValue];
progressSlider.maximumValue = totalTime;
…
}
// called on a one-second repeating timer
- (void)updateSlider {
progressSlider.value = musicPlayer.currentPlaybackTime;
[progressSlider setValue:musicPlayer.currentPlaybackTime animated:YES];
}
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.