gpt4 book ai didi

ios - Swift Avplayer - 当点击 'Play' 时,停止所有其他 tableviewcells 播放

转载 作者:行者123 更新时间:2023-12-01 18:34:32 28 4
gpt4 key购买 nike

我的主页是一个表格 View ,每个单元格都有一个播放按钮(单击时会创建 AVAudioPlayer 实例)。问题是我可以在多个单元格上单击播放,它们都会同时播放。我试图弄清楚单击任何播放按钮时如何暂停其他单元格。

这是我的 TableViewCell 中的播放按钮代码文件:

@IBAction func playButtonTapped(_ sender: UIButton) {

if self.audioPlayer != nil {
if self.audioPlayer.isPlaying {
self.audioPlayer.pause()
self.playbutton.setImage(#imageLiteral(resourceName: "bluePlay"), for: .normal)
}
else {
self.audioPlayer.play()
self.playbutton.setImage(#imageLiteral(resourceName: "bluePause"), for: .normal)
}
return
}
do {
self.audioPlayer = try AVAudioPlayer(data: self.audioFile!)
self.audioPlayer.prepareToPlay()
self.audioPlayer.delegate = self as? AVAudioPlayerDelegate
self.audioPlayer.play()
self.playbutton.setImage(#imageLiteral(resourceName: "bluePause"), for: .normal)

let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
} catch let error as NSError {
print("audioSession error: \(error.localizedDescription)")
}
} catch {
print(#line, error.localizedDescription)
}
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(HomeTableViewCell.updateProgress)), userInfo: nil, repeats: true)
}

我一直在尝试协议(protocol),试图编辑 TableViewVCTableViewCellVC ,但我不太明白。

最佳答案

由于您在一个单元格中有一个音频播放器,因此您需要一种方法来通知所有其他单元格已单击音频播放器。您可以通过在每个 UITableViewCell 中创建一个闭包来实现此目的。并将其分配到 cellForRow .每当单击播放按钮时,关闭将被触发并在您的 UIViewController 内您将遍历所有可见单元格并在单击的单元格中播放播放器之前暂停它们。像这样的东西:

class CustomTableViewCell : UITableViewCell{

var playButtonTapped : (()->())?
@IBAction func playButtonTapped(_ sender: UIButton) {
playButtonTapped?()
//rest of the code comes below
}
}


class TableViewController : UIViewController, UITableViewDataSource{

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
....
cell.playButtonTapped = {
for tempCell in tableView.visibleCells{
if let ultraTempCell = tempCell as? CustomTableViewCell, ultraTempCell != cell /* or something like this */{
//pause the player here
}
}
}
}
}

或者 ,你可以做的是,而不是在每个单元格中都有一个玩家,只需在 UIViewController 中创建一个玩家。并根据单击的单元格,只需更改里面的歌曲。

关于ios - Swift Avplayer - 当点击 'Play' 时,停止所有其他 tableviewcells 播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62334552/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com