我有一个包含所有歌曲的tableView(通过MediaPlayer导入),当我选择tableView的一个单元格时,我想播放所选的歌曲。
现在我的代码是这样的:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
MPMusicPlayerController().play()
}
但是当我选择一首歌时,它会播放普通音乐播放器中当前正在播放的歌曲,而不是我在我的应用中点击的歌曲。 如何让MusicPlayer知道我选择了哪首歌?
答案 0 :(得分:0)
注意 :鉴于此问题在此答案前6个月被提出并且没有任何回复,并且没有指定哪个版本的Swift,我我正在回答Swift 3。
我正在开发一款功能相似的应用。以下是我编写的两个函数(根据您的情况稍作修改):
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
}
然后您需要将代码更改为:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
setSong(songNamesArray[indexPath.row]) // Where songNamesArray is an array of Strings of the song names
MPMusicPlayerController().play()
}
如果您没有获取阵列中所有歌曲名称的功能,可以使用此功能:
func getSongNames() -> [String]{
var names = [String]()
let songs = getSongs()
for song in songs {
names.append("\(song.value(forProperty: MPMediaItemPropertyTitle)!)")
}
return names
}