首页 > 解决方案 > 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)
}

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

标签: iosswiftiphone

解决方案


由于您在一个单元格中有一个音频播放器,因此您需要一种方法来通知所有其他单元格已单击音频播放器。您可以通过在 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,根据点击的单元格,只需更改里面的歌曲。


推荐阅读