在集合视图中使用 AVPlayer 播放音频

时间:2021-03-13 21:53:31

标签: swift xcode uicollectionview avplayer

我正在使用 AVPlayer 在 Collection View Cells(Radio App)中播放音频。应用程序有效,但是,如果点击所有单元格上的播放按钮,所有电台一起播放,直到手动停止(请参见两个播放器同时播放的屏幕截图)。

我想做的是,如果按下一个单元格上的播放按钮,其他正在播放的玩家应该停止。任何帮助将不胜感激。

player = AVPlayer(url: "some url")
  func togglePlayer() {
        if player?.rate != 0 {
            player?.pause()
            self.playButton.setBackgroundImage(UIImage(systemName: "play.circle"), for: .normal)
        } else {
            player?.play()
            self.playButton.setBackgroundImage(UIImage(systemName: "stop"), for: .normal)
        }
    }

all players playing simultaneously

2 个答案:

答案 0 :(得分:1)

你可以试试

1- 在 vc 内制作玩家对象

2- 将单元格内按钮的播放动作添加到 vc 最好使用 addTarget 动作

3- 在 vc 中添加当前 playIndex 最初使其为零 Int

4- 将按钮标签设置为 indexPath.row iside celloForRowAt 并播放按钮状态为 indexpath.row 是否等于 playIndex

5- 在按钮操作中将 playIndex 设置为 sender.tag

6- 刷新收藏并开始播放选定的网址

答案 1 :(得分:1)

我要做的是添加

func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        collectionView.indexPathsForSelectedItems?.filter({ $0.section == indexPath.section }).forEach({ collectionView.deselectItem(at: $0, animated: false) })
        
        return true
    }

这将使一次只能选择给定部分中的一个单元格 或

func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        collectionView.indexPathsForSelectedItems?.forEach({ collectionView.deselectItem(at: $0, animated: false) })
        
        return true
    }

这将使得一次只能选择任何给定部分中的一个单元格。

所以选择您喜欢的任何一个并覆盖自定义单元格中的 isSelected 并在 isSelected 为 true 时播放,并在 isSelected 为 false 时暂停。

public override var isSelected: Bool {
        didSet {
            switch self.isSelected {
            case true:
                //play audio
            case false:
                //pause audio
            }
        }
    }