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

Fir*_*ist 4 audio objective-c mpmediaquery ios

我试图发挥MPMedaiItemMPMusicPlayerControlleriOS中.在我的情况下,我有一个UITableView播放播放列表中的歌曲.当我点按相机时UITableView,我想要播放那首歌MPMusicPlayerController.当我点击下一步按钮时,我还想跳过播放列表中的下一首歌曲.我该怎么玩?

以下是我在didSelectedMethod of 中编写的一些代码UITableView.那不起任何作用.

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

    MPMediaItem *item = [songs representativeItem ];

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

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

    [self.player play ];
Run Code Online (Sandbox Code Playgroud)

Mic*_*lum 9

我知道这是有点晚了,但你的问题是,MPMusicPlayerControllernowPlayingItem属性需要一个MPMediaItem对象,你传递一个NSString包含资产的URL.这是一个如何实现这一目标的例子.

MPMusicPlayerController *controller = [MPMusicPlayerController iPodMusicPlayer];

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

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

[controller prepareToPlay];
[controller play];
Run Code Online (Sandbox Code Playgroud)


小智 3

我发现在这样的实例中使用 AVPlayer 更容易。

在头文件中声明 AVPlayer 对象;

AVPlayer *audioPlayer;
Run Code Online (Sandbox Code Playgroud)

然后在您的方法文件中使用类似以下内容的内容:

if(!audioPlayer){
   audioPlayer = [[AVPlayer alloc] initWithURL:[item valueForProperty:MPMediaItemPropertyAssetURL]];
} else {
   [audioPlayer replaceCurrentItemWithPlayerItem:[AVPlayerItem playerItemWithURL:itemURL]];
}
[audioPlayer play];
Run Code Online (Sandbox Code Playgroud)