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 shows songs from a playlist. When I click a cell on a UITableView , I want to play this song using MPMusicPlayerController . And I also want to skip the following songs from the playlist when I click the "Next" button. How can I play it?

Here are some of my codes that write to the didSelected UITableView Method. It 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 ]; 
+4
source share
2 answers

I know this is a little late, but your problem is that the MPMusicPlayerController nowPlayingItem property expects an MPMediaItem object and you pass it an NSString containing the asset url. Here is an example of how this can be done.

 MPMusicPlayerController *controller = [MPMusicPlayerController iPodMusicPlayer]; MPMediaItemCollection *collection = [[MPMediaItemCollection alloc] initWithItems:arrayOfMediaItems]; MPMediaItem *item = [collection representativeItem]; [controller setQueueWithItemCollection:collection]; [controller setNowPlayingItem:item]; [controller prepareToPlay]; [controller play]; 
+8
source

It’s easier for me to use AVPlayer in a similar instance.

declares an AVPlayer object in your header file;

 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]; 
+3
source

All Articles