简体   繁体   中英

How to play MPMediaItem in MPMusicPlayerController in iOS?

I am trying to play MPMedaiItem in MPMusicPlayerController in iOS. In my case , i have a UITableView that show songs from playlist. When i tap cell on UITableView , i want to play that song with 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 . 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. 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.

in your header file declare the AVPlayer object;

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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