I would like to skip to another song using the index number of an item (that you can find with playlist.indexOfNowPlayingItem). Is there an easy way to do that with a function like mediaplayer.skipToNextItem but setting the index number ( for example mediaplayer.skipToItem(4) if i want to skip to the fourth item of my playlist) ?
2 Answers
If you check Apple's documentation, you can see that there are only methods for skipping to next, beginning and previous item. However there is a property nowPlayingItem
which enables us to either get current track, or set track to play, question is how did you set you current queue of songs...
Let's assume you're using:
1. Media item collection:
var songs = [song1, song2]
var player = MPMusicPlayerController.applicationMusicPlayer()
var collection = MPMediaItemCollection(items: songs)
player.setQueueWithItemCollection(collection)
So to set new song to play we just do this:
player.nowPlayingItem = song2 (it must be already in our collection)
Or if you want to use index number, since we have our songs in array, we can do also:
player.nowPlayingItem = songs[1]
2. Media Query
var query = MPMediaQuery.songsQuery() // query of songs sorted by name
var songs = query.items as NSarray
var player = MPMusicPlayerController.applicationMusicPlayer()
player.setQueueWithQuery(query)
Now to set new song to play we just do this:
player.nowPlayingItem = songs[1]

- 3,829
- 7
- 38
- 73
-
First, thanks for your quality answer ! But doing as you said using the Media Query it tell me "use of undeclared type NSArray" after declaring songs. I tried the first way creating a Media Item collection with my query but after player.nowPlayingItem = songs[1] it tell me "Cannot subscript a value of type MPMediaItem? with an index of type (). So i searched for other questions about nowPlayingItem and i found the answer, witch is to create a collection, set queue with that collection, and then set the song to play like that : player.nowPlayingItem = collection.items[1] – bennmen Sep 12 '15 at 13:51
The solution is, creating a collection as MPMediaItemCollection
, to set the song to play with : player.nowPlayingItem = collection.items[1]
for example :
var query = MPMediaQuery.songsQuery()
var collection = MPMediaItemCollection(items: query.items!) //it needs the "!"
let player = MPMusicPlayerController.applicationMusicPlayer()
player.setQueueWithItemCollection(collection)
player.nowPlayingItem = collection.items[1]
Note : Ifound the answer here : Play Song at specific index of MPMediaItemCollection in Swift