valerio0999
valerio0999

Reputation: 12138

youtube iframe api stopping a video when the other is playing

i have a slider with multiple videos in it. i would like to be able to stop a video (if it's playing) when another one is played.

i'm not a js expert so i'm having some troubles making it work.

i've created this pen: https://codepen.io/vlrprbttst/pen/eYpMrmB?editors=1010 as a starting point but i have no idea how to go on. I guess this part has something to do with what i'm looking for:

events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }

but i'm not sure how to use it :/

i used to use a method that doesn't always work, and it relies on a complex system with an invisible cover of the iframe that triggers the play/pause of the video with jquery but it doesn't always work (you can see it here: https://codepen.io/vlrprbttst/pen/vxrWzQ). I've been looking online but all i can find is multiple videos playing all at once.

any suggestions on how to detect a video playing and stopping it if a different one is played on the same page? with or without jquery is fine.

thank you so much in advance

Upvotes: 0

Views: 3298

Answers (1)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20954

I'd suggest that you create your YouTube players and store each om them in an array. This way you can always loop over each one of them in a callback and control what should be happening.

First create an empty array in which to store the players and (optionally) an array which holds object with the id of the video and the element to create a player in.

let youtubePlayers = [];
const youtubeVideosSources = [
  {
    id: 'M7lc1UVf-VE',
    player: 'player1'
  },
  {
    id: 'VFQB1zE9zYU',
    player: 'player2'
  }
];

In your ready callback use the map() method of the array with id's and players to create a new array of YouTube players and store them in the empty array you created earlier. Or in this case, overwrite the value of the variable.

function onYouTubeIframeAPIReady() {
  youtubePlayers = youtubeVideosSources.map(({ id, player }) => new YT.Player(player, { 
    height: '360',
    width: '640',
    videoId: id,
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  }));
}

Then in the onPlayerStateChange callback loop over each player and stop them if they are not the currently activated player and are actually playing. You can check each players state with the getPlayerState() method.

function onPlayerStateChange(event) {
  const playing = YT.PlayerState.PLAYING;
  if (event.data === playing) {
    for (const player of youtubePlayers) {
      if (player !== event.target && player.getPlayerState() === playing) {
        player.stopVideo();
      }
    }
  }
}

Upvotes: 1

Related Questions