heavyguidence
heavyguidence

Reputation: 373

Playing Audio using AVPlayer in Collection View

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)
        }
    }

all players playing simultaneously

Upvotes: 0

Views: 856

Answers (2)

shadow of arman
shadow of arman

Reputation: 425

What I would do is to add

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

This will make it so only one cell inside a given section can be selected at once or

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

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.

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

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

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 action

3- Add current playIndex inside the vc initially make it a nil Int

4- Set the button tag to indexPath.row iside celloForRowAt and play button status to whether indexpath.row equal to playIndex or not

5- Inside the button action set playIndex to sender.tag

6- Refresh the collection and start playing the selected url

Upvotes: 1

Related Questions