Search code examples
swiftmedia-playerapple-musickit

Get Shuffled Tracks from Media Player


I want to get the queue from the Media Player. I believe that I can't read the queue though (is this correct?) and that I can only get the queue when I set it, like when I select a certain playlist to play. However I'm struggling to get the shuffled queue.

            let musicPlayerController = MPMusicPlayerController.systemMusicPlayer
            let myMediaQuery = MPMediaQuery.songs()
            let predicateFilter = MPMediaPropertyPredicate(value: chosenPlaylist, forProperty: MPMediaPlaylistPropertyName)
            myMediaQuery.filterPredicates = NSSet(object: predicateFilter) as? Set<MPMediaPredicate>
            musicPlayerController.setQueue(with: myMediaQuery)
            musicPlayerController.repeatMode = .all
            musicPlayerController.shuffleMode = .songs
            musicPlayerController.play()
            for track in myMediaQuery.items! {
                print(track.value(forProperty: MPMediaItemPropertyTitle)!)
            } // here I don't get the shuffled order that is going to play, just get the original order of the playlist

I need the shuffled as I want to be able to display what's going to play next.


Solution

  • I've had trouble with .shuffleMode in the past. Call shuffled() on the collection instead:

    // shuffle
    func shufflePlaylist() {
    
        let query = MPMediaQuery.songs()
        let predicate = MPMediaPropertyPredicate(value: "Art Conspiracy",
                                                 forProperty: MPMediaPlaylistPropertyName,
                                                 comparisonType: .equalTo)
        query.addFilterPredicate(predicate)
    
        guard let items = query.items else { return }
        let collection = MPMediaItemCollection(items: items.shuffled())
    
        player.setQueue(with: collection)
        player.prepareToPlay()
        player.play()
    }