J.Vongehr
J.Vongehr

Reputation: 333

How to tell the MediaPlayer which song to play?

I have a tableView with all my songs (imported via MediaPlayer) and when i select a cell of the tableView I want to play the selected song.

Right now my code is like this:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    MPMusicPlayerController().play()
}

but when I select a song, it plays the song that is the currently playing item in the normal music player, and not the song I clicked in my app. How can I let the MusicPlayer know which song I selected?

Upvotes: 1

Views: 1097

Answers (1)

Wyetro
Wyetro

Reputation: 8578

Note: Given that this question was asked 6 months before this answer and has no responses what so ever and does not specify which version of Swift, I am answering with Swift 3.

I'm working on an app with similar functionalities. Here are two functions I wrote (that are slightly modified for your situation):

import MediaPlayer

func getSongs()->[MPMediaItemCollection] {

    let songsQuery = MPMediaQuery.songs() //Gets the query
    let songs = songsQuery.collections //Gets the songs

    if songs != nil {
        return songs! // Return songs if they exist

    } else {
        return [] // Return failed
    }

}

func setSong(song:String) -> Bool { // Pass name of song

    let songs = getSongs() // Get all songs
    for sng in songs { // Look for song
        if String(describing: sng.value(forProperty: MPMediaItemPropertyTitle)!) == song { // If you found it
            MPMusicPlayerController.systemMusicPlayer().setQueue(with: sng) // Set it
            songSet = true // Set correctly
            break
        }
    }    

    return songSet // Return if you set it correctly
}

And then you need to change your code to:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
     setSong(songNamesArray[indexPath.row]) // Where songNamesArray is an array of Strings of the song names
     MPMusicPlayerController().play()
}

In the case that you don't have a function to get all of the names of the songs in the array you can use this:

func getSongNames() -> [String]{

    var names = [String]()
    let songs = getSongs()
    for song in songs {
        names.append("\(song.value(forProperty: MPMediaItemPropertyTitle)!)")
    }

    return names
}

Upvotes: 0

Related Questions