I want to show a video accordingly to the selected cell in my tableview. I want to show the video in a view in my vc.
The following code is showing the correct videos when the cells are tapped but whenever i select a new cell the audio from the old video is still there. How can i remove it ?
Setting up the view in my vc:
func setupView(for url: URL) {
let player = AVPlayer(url: url)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.videoView.bounds
self.videoView.layer.addSublayer(playerLayer)
player.play()
}
didSelectRow code:
let selectedExercise = exercises[indexPath.row]
setupView(for: URL(string: selectedExercise.videoUrl)!)
My guess is that i should pause/stop the previous video before showing the new one. But i don't know how to. Thanks a lot!
It's happend because you create new instance of AVPlayer every tap.
To solve your problem, you need to move
let player = AVPlayer(url: url)
outside of setupView()
and call it only once. You could move it in init()
for example.
For updating asset (video url) in setupView()
you could use
player.replaceCurrentItem(with: AVPlayerItem(url: url))
.