[英]How to play music file after fetching list of songs from Music Library?
在我的應用程序中,我必須制作音樂庫。 所以我必須從音樂庫中獲取歌曲。 我完成了直到這個再見。
Test_MusicLibraryAppDelegate *appDeleg = (Test_MusicLibraryAppDelegate *)[[UIApplication sharedApplication]delegate];
//NSMutableDictionary *musicList = [NSMutableDictionary dictionary];
MPMediaQuery *query = [[MPMediaQuery alloc] init];
[query addFilterPredicate:[MPMediaPropertyPredicate
predicateWithValue:[NSNumber numberWithInteger:(MPMediaTypeMusic)]
forProperty:MPMediaItemPropertyMediaType]];
for (MPMediaItem* item in [query items]) {
[appDeleg.arryMusic addObject:item];
}
NSLog(@"Count :: %d ",[appDeleg.arryMusic count]);
[query release];
而不是在表視圖中顯示它。
當我必須在所選索引上播放歌曲時,我會獲取歌曲名稱但不知道如何播放該歌曲,
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
Test_MusicLibraryAppDelegate *appDeleg = (Test_MusicLibraryAppDelegate *)[[UIApplication sharedApplication]delegate];
// MPMediaItem *song = [appDeleg.arryMusic objectAtIndex:indexPath.row];
NSURL *aURL = [appDeleg.arryMusic objectAtIndex:indexPath.row];
//[song valueForProperty:MPMediaItemPropertyAssetURL];
[[self avPlayer] replaceCurrentItemWithPlayerItem:
[AVPlayerItem playerItemWithURL:aURL]];
[avPlayer play];
}
但我的聲音文件不會播放...
嘿,任何人都知道這個比幫助我..
謝謝AJPatel
您沒有在數組中存儲URL,而是存儲MPMediaItem
實例
您需要做的是從媒體項中提取資源URL。 你可以這樣做......
MPMediaItem *item = [appDeleg.arryMusic objectAtIndex:indexPath.row];
NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];
[[self avPlayer] replaceCurrentItemWithPlayerItem:[AVPlayerItem playerItemWithURL:url]];
[self.avPlayer play];
你必須初始化一個玩家對象(appdelegate將是一個好位置)
MPMusicPlayerController *musicPlayer; //in .h file
self.musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
[self.musicPlayer setRepeatMode:MPMusicRepeatModeNone];
[self.musicPlayer setShuffleMode:MPMusicShuffleModeOff];
[self.musicPlayer beginGeneratingPlaybackNotifications];
然后必須維護一個用於保存媒體元素的數組
MPMediaItemCollection * userMediaItemCollection; //在.h文件中@property(非原子,保留)MPMediaItemCollection * userMediaItemCollection; //在.h文件中
您必須將媒體項添加到陣列(輸入列表)並將其添加到mediacollection列表
[self setUserMediaItemCollection: [MPMediaItemCollection collectionWithItems: (NSArray *) inputList]];
將媒體收藏列表添加到播放器
[APP_DELEGATE.musicPlayer setQueueWithItemCollection: self.userMediaItemCollection];
現在玩
[APP_DELEGATE.musicPlayer play];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.