Marsman
Marsman

Reputation: 825

How do you use MPMediaItemPropertyPersistentID to play music in iPhone Music Player Framework?

My code sucessfully catalogs song names and ID's for my the entire music library. However, it will not actually play a song using this methodology and the console displays the following:

Message playbackState timed out.

Message nowPlayingItem timed out.

self.musicPlayer = [MPMusicPlayerController applicationMusicPlayer];

MPMediaQuery *everything = [[MPMediaQuery alloc] init];
NSArray *itemsFromGenericQuery = [everything items];
SongName = [[NSMutableArray alloc] init];
SongItem = [[NSMutableArray alloc] init];
NSString *songTitle;
NSString *songID;
//Collect names & ID for entire music library & put into arrays
for (MPMediaItem *song in itemsFromGenericQuery) {
songTitle = [song valueForProperty: MPMediaItemPropertyTitle];
[SongName addObject:songTitle];
songID = [song valueForProperty: MPMediaItemPropertyPersistentID];
[SongItem addObject:songID];
}

NSLog (@"%@", [SongName objectAtIndex:1]);
NSLog (@"%@", [SongItem objectAtIndex:1]);
// Play the second song in the list
MPMediaItemCollection *collection = [MPMediaItemCollection collectionWithItems:[NSArray arrayWithObject:[SongItem objectAtIndex:1]]];
[self.musicPlayer setQueueWithItemCollection:collection];
[self.musicPlayer play];

Upvotes: 3

Views: 3364

Answers (1)

Marsman
Marsman

Reputation: 825

Once again, I'll answer my own question. The issue was that collectionWithItems: expects an array of MPMediaItems, not an array of MPMediaItemPropertyPersistentIDs. Here is the working code for anyone who may have the same problem:

MPMediaQuery *everything = [[MPMediaQuery alloc] init];
NSArray *itemsFromGenericQuery = [everything items];
SongItem = [[NSMutableArray alloc] init];
for (MPMediaItem *song in itemsFromGenericQuery) {
   NSString *songTitle = [song valueForProperty: MPMediaItemPropertyTitle];
   //NSLog (@”%@”, songTitle);
   songID = [song valueForProperty: MPMediaItemPropertyPersistentID];
   //NSLog (@”%@”, songID);
   [SongItem addObject:songID];
}

//Choose the first indexed song
NSString *selectedTitle = [SongItem objectAtIndex:0];

//Use the MPMediaItemPropertyPersistentID to play the song
MPMediaPropertyPredicate *predicate = [MPMediaPropertyPredicate predicateWithValue:selectedTitle forProperty:MPMediaItemPropertyPersistentID];
MPMediaQuery *mySongQuery = [[MPMediaQuery alloc] init];
[mySongQuery addFilterPredicate: predicate];
[musicPlayer setQueueWithQuery:mySongQuery];
[musicPlayer play];

Upvotes: 6

Related Questions