我的应用程序获取歌曲列表和相应的URL以下载歌曲,然后将它们显示在表格视图中。
表视图具有歌曲列表,每个单元格代表一首歌曲,并设计为具有播放和暂停按钮以及显示歌曲标题的标签。
当我单击按钮时,它应该从播放图像更改为暂停图像并开始播放歌曲。当我单击暂停时,它应该停止播放歌曲并更改按钮图像以播放。如果我单击其他单元格上的按钮(以播放另一首歌曲),则当前歌曲应停止播放,而当前图像将停止播放。按钮应从暂停状态变为播放状态,并且单击的下一个按钮现在应具有与上述相同的功能。
我正在使用AVPlayer。
我对如何一次只播放一首歌曲以及更改相应按钮的图像感到困惑。
代码示例确实有帮助。
override func viewDidLoad() {
super.viewDidLoad()
do{
try
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
}catch let error{
print(error.localizedDescription)
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
-> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:
"songCell") as! SongCell
cell.onButtonTapped = {
let item = AVPlayerItem.init(url: "SONGS URL HERE")
if player == nil{
player = AVPlayer(playerItem:item)
player?.playImmediately(atRate: 1.0)
player?.automaticallyWaitsToMinimizeStalling = false
player?.play()
}else{
if (player?.rate != 0 && player != nil){
player?.pause()
player = nil
}
}
}
}
return cell
}
@IBAction func playPauseSong(_ sender: UIButton) {
var buttonTapped : (() -> Void)? = nil
if sender.isSelected == false{
sender.isSelected = true
}else{
sender.isSelected = false
}
if let onButtonTapped = self.onButtonTapped {
buttonTapped()
}
}