andreipitis / ASPVideoPlayer

A simple video player that allow animations to be performed on the view during playback.
MIT License
89 stars 43 forks source link

Playing multiple video at same time. #45

Closed Priyanka-14 closed 5 years ago

Priyanka-14 commented 5 years ago

when I used this player into tableview cell, multiple video's get played at same time, how to play only visible cell's video.

andreipitis commented 5 years ago

Hi @Priyanka-14,

The solution to your question is very specific to your use case. One way to do this would be to use the UITableViewDelegate methods to start the player in a specific cell and stop the other ones. If you have large cells, or if only one is visible at all times this should work:

extension ViewController: UITableViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
         //Get the cell at the center of the tableView
        if let indexPath = tableView.indexPathForRow(at: CGPoint(x: 0, y: scrollView.bounds.height / 2 + scrollView.contentOffset.y)),
            //Cast cell to custom class to access the player
            let cell = tableView.cellForRow(at: indexPath) as? TableCell {
            //Start the player in the center cell
            cell.playerView?.videoPlayerControls.play()

            //Get all visible cells and the index of the current cell
            var visible = tableView.visibleCells
            if let index = visible.firstIndex(of: cell) {

                //Remove the current cell from the visible array
                visible.remove(at: index)

                //Iterate over the remaining cells and stop the player
                for visibleCell in visible {
                    let playerCell = visibleCell as! TableCell
                    playerCell.playerView?.videoPlayerControls.stop()
                }
            }
        }
    }
}