I am using AVPlayer
to play Audio in Collection View Cells (Radio App). Application works, however, If play button on All cells is tapped, All stations play together, until manually stopped (please see the screenshot two players are playing at the same time).
What I would like to do is that if play button on one cell is pressed, other playing players should stop. Any help will be appreciated.
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)
}
}
2
Answers
You can try
1- Make the player object inside the vc
2- Add play action of button that’s inside the cell to the vc preferably with
addTarget
action3- Add current
playIndex
inside the vc initially make it a nilInt
4- Set the button tag to
indexPath.row
isidecelloForRowAt
and play button status to whetherindexpath.row
equal toplayIndex
or not5- Inside the button action set
playIndex
tosender.tag
6- Refresh the collection and start playing the selected url
What I would do is to add
This will make it so only one cell inside a given section can be selected at once
or
This will make it so only one cell in any given section can be selected at once.
so pick which ever you prefer and override
isSelected
in your custom cell and make it play when isSelected is true and pause when isSelected is false.