5

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 ];
Devolus
  • 21,661
  • 13
  • 66
  • 113
Fire Fist
  • 7,032
  • 12
  • 63
  • 109

2 Answers2

10

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];
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
  • iPodMusicPlayer is long outdated. One alternative is `MPMusicPlayerController.systemMusicPlayer`. – Jonny Jan 21 '23 at 14:29
3

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];
Tom O'Reilly
  • 113
  • 1
  • 8