![](/img/trans.png)
[英]How to play background music with MPMusicPlayerController's applicationMusicPlayer in iOS?
[英]How to play MPMediaItem in MPMusicPlayerController in iOS?
我試圖在iOS中的MPMusicPlayerController
中播放MPMedaiItem
。 在我的情況下,我有一個UITableView
顯示播放列表中的歌曲。 當我點擊UITableView
單元格時,我想用MPMusicPlayerController
播放該歌曲。 當我點擊下一步按鈕時,我還想跳過播放列表中的下一首歌曲。 我該怎么玩?
以下是我在UITableView
didSelected
方法中編寫的一些代碼。 那不起任何作用。
MPMediaItemCollection *songs = [self.arrayOfSongs objectAtIndex:indexPath.row ];
MPMediaItem *item = [songs representativeItem ];
NSLog(@"%@",[item valueForProperty:MPMediaItemPropertyTitle ]);
[self.player setNowPlayingItem:[item valueForProperty:MPMediaItemPropertyAssetURL]];
[self.player play ];
我知道這有點晚了,但問題是MPMusicPlayerController
的nowPlayingItem
屬性需要一個MPMediaItem
對象,並且你傳遞的是一個包含資產URL的NSString
。 這是一個如何實現這一目標的例子。
MPMusicPlayerController *controller = [MPMusicPlayerController iPodMusicPlayer];
MPMediaItemCollection *collection = [[MPMediaItemCollection alloc] initWithItems:arrayOfMediaItems];
MPMediaItem *item = [collection representativeItem];
[controller setQueueWithItemCollection:collection];
[controller setNowPlayingItem:item];
[controller prepareToPlay];
[controller play];
我發現在這樣的實例中使用AVPlayer更容易。
在頭文件中聲明AVPlayer對象;
AVPlayer *audioPlayer;
然后在你的方法文件中使用類似的東西:
if(!audioPlayer){
audioPlayer = [[AVPlayer alloc] initWithURL:[item valueForProperty:MPMediaItemPropertyAssetURL]];
} else {
[audioPlayer replaceCurrentItemWithPlayerItem:[AVPlayerItem playerItemWithURL:itemURL]];
}
[audioPlayer play];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.