Retrieving the currently being played music track

One question I keep hearing is “Can you find out what music track a user is listening to? as I want to use it for …”, where the reason usually revolves around posting it to a social network network site, or using it as IM status. Thankfully retrieving the currently being played music track is very easy thanks to the MediaPlayer Framework.

Each application has its own MPMusicPlayerController, but it also has access to the iPod’s MPMusicPlayerController, using the class method iPodMusicPlayer.

MPMusicPlayerController *iPodMusicPlayerController = [MPMusicPlayerController iPodMusicPlayer];

After you have got the iPod music player, you can then get the now playing item

MPMediaItem *nowPlayingItem = [iPodMusicPlayerController nowPlayingItem];

If the now playing item is nil, you know that the user is not playing a music track on their iPod.

Unlike many of the other APIs in iOS, you can’t access information such as the track name, via a simple string property. You have to use one of the following keys:

NSString *const MPMediaItemPropertyPersistentID;
NSString *const MPMediaItemPropertyMediaType; 
NSString *const MPMediaItemPropertyTitle;
NSString *const MPMediaItemPropertyAlbumTitle; 
NSString *const MPMediaItemPropertyArtist; 
NSString *const MPMediaItemPropertyAlbumArtist; 
NSString *const MPMediaItemPropertyGenre;
NSString *const MPMediaItemPropertyComposer; 
NSString *const MPMediaItemPropertyPlaybackDuration;
NSString *const MPMediaItemPropertyAlbumTrackNumber;
NSString *const MPMediaItemPropertyAlbumTrackCount;
NSString *const MPMediaItemPropertyDiscNumber;
NSString *const MPMediaItemPropertyDiscCount;
NSString *const MPMediaItemPropertyArtwork;
NSString *const MPMediaItemPropertyLyrics;
NSString *const MPMediaItemPropertyIsCompilation;  
NSString *const MPMediaItemPropertyReleaseDate;
NSString *const MPMediaItemPropertyBeatsPerMinute;
NSString *const MPMediaItemPropertyComments;
NSString *const MPMediaItemPropertyAssetURL;

And then query the Media Player Item, using the instance method valueForProperty:.

NSString *itemTitle = [nowPlayingItem valueForProperty:MPMediaItemPropertyTitle];

And thus you will end up with a code snippet like this:

MPMusicPlayerController *iPodMusicPlayerController = [MPMusicPlayerController iPodMusicPlayer];

MPMediaItem *nowPlayingItem = [iPodMusicPlayerController nowPlayingItem];   

if (nowPlayingItem) {
    NSString *itemTitle = [nowPlayingItem valueForProperty:MPMediaItemPropertyTitle];
    NSLog(@"User is playing the following song: %@",itemTitle);
} else {
    NSLog(@"User is not playing a song");

As always this is just a small code snippet to get you started. There are situations for instance, where the user can have a now playing item that has no title (strange I know). So as always you will have to handle these edge cases appropriately.