Skip to content Skip to sidebar Skip to footer

Youtube Api - Loop Video Between Set Start And End Times

I've managed to start the video and end the video at the times I need, but is there any way to loop this? The loop option doesn't seem to be doing much. Fiddle: https://jsfiddle.n

Solution 1:

You can implement onStateChange callback & load the video with the same startSeconds & endSeconds parameter with loadVideoById :

// Load the IFrame Player API code asynchronously.var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var videoId = 'M7lc1UVf-VE';
var startSeconds = 36;
var endSeconds = 45;

// Replace the 'ytplayer' element with an <iframe> and// YouTube player after the API code downloads.var player;

var playerConfig = {
  height: '360',
  width: '640',
  videoId: videoId,
  playerVars: {
    autoplay: 1, // Auto-play the video on loadcontrols: 0, // Show pause/play buttons in playershowinfo: 0, // Hide the video titlemodestbranding: 1, // Hide the Youtube Logofs: 1, // Hide the full screen buttoncc_load_policy: 0, // Hide closed captionsiv_load_policy: 3, // Hide the Video Annotationsstart: startSeconds,
    end: endSeconds,
    autohide: 0, // Hide video controls when playing
  },
  events: {
    'onStateChange': onStateChange
  }
};

functiononYouTubePlayerAPIReady() {
  player = newYT.Player('ytplayer', playerConfig);
}

functiononStateChange(state) {
  if (state.data === YT.PlayerState.ENDED) {
    player.loadVideoById({
      videoId: videoId,
      startSeconds: startSeconds,
      endSeconds: endSeconds
    });
  }
}

Here is a Fiddle

Solution 2:

Iterating on Bertrand Martel's great answer above:

If you're looping on the same video, I've found you can minimize the delay in between loops by calling player.seekTo(startSeconds)instead of player.loadVideoById(...). Here is a fiddle comparing the performance of both approaches.

Post a Comment for "Youtube Api - Loop Video Between Set Start And End Times"