WunDaii
WunDaii

Reputation: 2312

Next Song in MediaItemCollection?

How do I find out the name of the next item to be played in an MPMediaItem collection? I would prefer to store this as an MPMediaItem.

I have a songsViewController that has a tableView of all the songs. This is my code for didSelectRowAtIndexPath:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MPMediaItem *selectedItem;

    selectedItem = [[songs objectAtIndex:indexPath.row] representativeItem];

    MPMusicPlayerController *musicPlayer = [MPMusicPlayerController iPodMusicPlayer];

    [musicPlayer setQueueWithItemCollection:[MPMediaItemCollection collectionWithItems:[songsQuery items]]];

    [musicPlayer setNowPlayingItem:selectedItem];

    nowPlayingViewController *nowPlaying = [[rightSideMenuViewController alloc]
                                            initWithNibName:@"nowPlayingViewController" bundle:nil];

    [self presentViewController:nowPlaying animated:YES completion:nil];

    [musicPlayer play];

}

I have a UILabel on my nowPlayingViewController which pops up when the user has selected a song. I would like to store the title of the next item in the MediaItemCollection/queue to be in that UILabel - so it is a preview of what the next song is.

Any help would be much appreciated, thanks! :)

Upvotes: 0

Views: 464

Answers (2)

Luke Schoen
Luke Schoen

Reputation: 4503

MPMusicPlayerController provides the following instance methods to quickly skip to your next or previous song:

[musicPlayer skipToNextItem];

[musicPlayer skipToPreviousItem];

Upvotes: 0

Larme
Larme

Reputation: 26006

Keep your list (since your can't access at musicplayer queue).

@property (nonatomic, strong) NSArray *playlist;

When you do:

 [musicPlayer setQueueWithItemCollection:[MPMediaItemCollection collectionWithItems:[songsQuery items]]];

Add:

playlist = [songsQuery items];

To fetch your previous/next:

-(MPMediaItem *)nextItem
{
     int currentIndex = [musicPlayer indexOfNowPlayingItem];
     MPMediaItem *nextItem = [playlist objectAtIndex:currentIndex+1];
     return nextItem
}

-(MPMediaItem *)previousItem
{
     int currentIndex = [musicPlayer indexOfNowPlayingItem];
     MPMediaItem *previousItem = [playlist objectAtIndex:currentIndex-1];
     return previousItem;
}

Important note:
I didn't check if the current item was the first/last (according if you want previous/next) item in playlist. So be careful with bounds of the NSArray, or you'll get a:

NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index Z beyond bounds [X .. Y]

So does previousItem "exists"? Does nextItem "exists"?

You may also have to look at:

@property (nonatomic) MPMusicRepeatMode repeatMode

In case that the nextItem may be the first item, or the previous item the last one.

Upvotes: 1

Related Questions