N Sreelekh
N Sreelekh

Reputation: 33

multiple audios playing same time issue

This is the code for my collection view cell,

class FeedVideoCollectionViewCell: UICollectionViewCell {
    
    @IBOutlet var audioBtn: UIButton!
    @IBOutlet var videoView: AVPlayerView!
    
    var player : AVPlayer?
    var actionComplete: ((_ index:Int) -> Void)?
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    
    @IBAction func audioBtnAction(_ sender: UIButton) {
        if player?.isMuted ?? false {
            actionComplete?(sender.tag)
            player?.isMuted = false
            audioBtn.setImage(UIImage(named: "HomeFeedVolOn"), for: .normal)
        } else {
            player?.isMuted = true
            audioBtn.setImage(UIImage(named: "HomeFeedVolOff"), for: .normal)
        }
    }
    
    func setData(_ model:Post) {
        if (model.media?.count ?? 0) > 0 {
            let videoURL = URL(string: model.media?[0].sourcePath ?? "")
            player = AVPlayer(url: videoURL!)
            let castedLayer = videoView.layer as! AVPlayerLayer
            castedLayer.player = player
            player?.isMuted = true
            player?.play()
        }
    }
}

class AVPlayerView: UIView {
    override class var layerClass: AnyClass {
        return AVPlayerLayer.self
    }
}

The issue is when I turn "on" one audio and it's "on" while I play the next, both audios are getting played.

I want to turn off the previous when new audio is playing.

is there is any way apart from reloading the entire thing.

Upvotes: 0

Views: 76

Answers (1)

cora
cora

Reputation: 2102

In your tableview controller keep a variable of type FeedVideoCollectionViewCell. On didSelectCell check for nil, if not, turn the audio off. Assign selected cell to the global variable. Start playback..

Upvotes: 1

Related Questions