简体   繁体   English

如何在iOS中的MPMusicPlayerController中播放MPMediaItem?

[英]How to play MPMediaItem in MPMusicPlayerController in iOS?

I am trying to play MPMedaiItem in MPMusicPlayerController in iOS. 我试图在iOS中的MPMusicPlayerController中播放MPMedaiItem In my case , i have a UITableView that show songs from playlist. 在我的情况下,我有一个UITableView显示播放列表中的歌曲。 When i tap cell on UITableView , i want to play that song with MPMusicPlayerController . 当我点击UITableView单元格时,我想用MPMusicPlayerController播放该歌曲。 And i also want to skip next songs from playlist when i tap Next Button. 当我点击下一步按钮时,我还想跳过播放列表中的下一首歌曲。 How can i play it? 我该怎么玩?

Here is some of my codes that write in didSelected Method of UITableView . 以下是我在UITableView didSelected方法中编写的一些代码。 That doesn't play anything. 那不起任何作用。

    MPMediaItemCollection *songs = [self.arrayOfSongs objectAtIndex:indexPath.row ];

    MPMediaItem *item = [songs representativeItem ];

    NSLog(@"%@",[item valueForProperty:MPMediaItemPropertyTitle ]);

    [self.player setNowPlayingItem:[item valueForProperty:MPMediaItemPropertyAssetURL]];

    [self.player play ];

I know this is a little late, but your problem is that MPMusicPlayerController 's nowPlayingItem property expects a MPMediaItem object, and you're passing it an NSString containing the URL of the asset. 我知道这有点晚了,但问题是MPMusicPlayerControllernowPlayingItem属性需要一个MPMediaItem对象,并且你传递的是一个包含资产URL的NSString Here's an example of how this could be accomplished. 这是一个如何实现这一目标的例子。

MPMusicPlayerController *controller = [MPMusicPlayerController iPodMusicPlayer];

MPMediaItemCollection *collection = [[MPMediaItemCollection alloc] initWithItems:arrayOfMediaItems];
MPMediaItem *item = [collection representativeItem];

[controller setQueueWithItemCollection:collection];
[controller setNowPlayingItem:item];

[controller prepareToPlay];
[controller play];

I find it easier to use AVPlayer in an instance like this. 我发现在这样的实例中使用AVPlayer更容易。

in your header file declare the AVPlayer object; 在头文件中声明AVPlayer对象;

AVPlayer *audioPlayer;

Then in your method file use something like: 然后在你的方法文件中使用类似的东西:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM