【发布时间】:2018-09-28 09:50:40
【问题描述】:
我有一些歌曲并在 tableview 中显示。当我按下单元格时,它正在播放歌曲。当我触摸同一个单元格时我想停下来,但如果我触摸另一个单元格,我想让它继续播放新歌。
extension SoundsViewController: UITableViewDataSource,UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return songs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = myTableView.dequeueReusableCell(withIdentifier: "soundsCell") as! SoundsTableViewCell
cell.soundPicture.image = UIImage(named: "cell1")
cell.soundLabel.text = songs[indexPath.row]
cell.playStopImage.image = UIImage(named: "play")
if selectedItemIndex == indexPath.row {
cell.playStopImage.image = UIImage(named: "pause")
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 120
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectedItemIndex = indexPath.row
playSong(song: songs[indexPath.row], selectedItemIndex: selectedItemIndex!)
self.myTableView.reloadData()
}
}
func playSong(song: String, selectedItemIndex: Int){
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: song, ofType: "mp3")!))
audioPlayer.numberOfLoops = -1
audioPlayer.play()
var audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayback)
}catch{
print(error)
}
}catch{
print(error)
}
}
【问题讨论】:
标签: ios swift uitableview avaudioplayer