我有類似的問題。但我用MPMusicPlayerController
我需要保存選定的音樂信息從音樂庫以後播放,但我couldnt。
我存儲在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];
}
非常感謝您對這個解決方案,但我不能用別的比AVAudioPlayer,我不希望將數據存儲在我的結束,只是引用它,僅此而已,複製的數據是不是一種選擇,因爲我的應用程序可能會映射整個音樂庫。 –