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

My code successfully catalogs song names and IDs for my entire music library. However, it will not play the song using this methodology, and the console will display the following:

Message playback time. Waiting time.

Message nowPlayingItem timeout.

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];
+3
source share
1 answer

Once again, I will answer my question. The problem was that collectionWithItems: expects an array of MPMediaItems, not an array of MPMediaItemPropertyPersistentID. Here is the working code for those 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];
+6
source

Source: https://habr.com/ru/post/1782925/


All Articles