ios - Swift Avplayer - 当点击“播放”时,停止所有其他 tableviewcells 播放
问题描述
我的主页是一个表格视图,每个单元格都有一个播放按钮(单击时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)
}
我一直在尝试协议,尝试编辑TableViewVC
和TableViewCellVC
,但我不太明白。
解决方案
由于您在一个单元格中有一个音频播放器,因此您需要一种方法来通知所有其他单元格已单击音频播放器。您可以通过在 each 内部创建一个闭包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
,根据点击的单元格,只需更改里面的歌曲。
推荐阅读
- python - 如何在主要方法中正确引发自定义异常?
- html - CSS 用于特定字符的分词提示
- typescript - VSCode > 运行打字稿文件时找不到对应的JS
- google-cloud-platform - 名称字段列表在哪里 [dialogflow API VoiceSelectionParams 的名称字段]
- python-3.x - 将变量传递给在 Raspberry Pi 上实现的 Dialogflow 聊天机器人
- python - 带有可变“必填”字段的 Django 表单
- java - 是否可以在条件内递减计数器?
- tensorflow - 如何使用tensorflow.estimator只加载预训练模型的部分层参数
- django - 如何在具有多个模型的 django 详细信息视图中正确使用带有外键的过滤器方法
- linux - 以编程方式查找给定进程/pid的软件包和版本