我有一个类似的问题。但是我用MPMusicPlayerController
我需要从音乐库中保存选定的音乐信息以供以后播放,但我不能。
我将音乐数据存储在NSUserDefaults
这是我的代码
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection
{
if (mediaItemCollection) {
[appDel.musicPlayer setQueueWithItemCollection: mediaItemCollection];
if ([mediaItemCollection count] >0) {
[appDel.musicPlayer play];
}
NSArray* items = [mediaItemCollection items];
NSMutableArray* listToSave = [[NSMutableArray alloc] initWithCapacity:0];
for (MPMediaItem *mpItem in items) {
NSNumber *persistentId = [mpItem valueForProperty:MPMediaItemPropertyPersistentID];
[listToSave addObject:persistentId];
}
int songId = [[[NSUserDefaults standardUserDefaults] objectForKey:@"lastID"] intValue];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:listToSave];
if (editting) {
[[NSUserDefaults standardUserDefaults] setObject:data forKey:[NSString stringWithFormat:@"song%@",edittingSong.sqlId]];
}
else
{
[[NSUserDefaults standardUserDefaults] setObject:data forKey:[NSString stringWithFormat:@"song%d",songId+1]];
}
[[NSUserDefaults standardUserDefaults] synchronize];
[self updateMusicInfo];
}
[self dismissModalViewControllerAnimated: YES];
}
您可以使用任何您想要的密钥。
读取数据并在播放器中设置队列。
NSMutableArray *theList = [[NSMutableArray alloc] initWithCapacity:0];
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"song%@",edittingSong.sqlId]];
NSArray *decodedData = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[theList addObjectsFromArray:decodedData];
NSMutableArray *allTheSongs = [[NSMutableArray alloc] initWithCapacity:0];
for (int i = 0; i < [theList count]; i++) {
MPMediaQuery *songQuery = [MPMediaQuery songsQuery];
[songQuery addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:[theList objectAtIndex:i] forProperty:MPMediaItemPropertyPersistentID]];
NSArray *songs = [songQuery items];
[allTheSongs addObjectsFromArray: songs];
}
f ([allTheSongs count] >0) {
MPMediaItemCollection *currentQueue = [[MPMediaItemCollection alloc] initWithItems:allTheSongs];
[appDel.musicPlayer setQueueWithItemCollection:currentQueue];
[appDel.musicPlayer play];
}