我的代码成功地为我的整个音乐库编目了歌曲名称和ID。但是,它实际上不会使用此方法播放歌曲,控制台会显示以下内容:
消息播放状态超时。
消息nowPlayingItem超时。
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];
答案 0 :(得分:6)
再一次,我会回答我自己的问题。问题是collectionWithItems:需要一个MPMediaItem数组,而不是MPMediaItemPropertyPersistentIDs数组。以下是可能遇到同样问题的任何人的工作代码:
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];