0

I am having a very frustrating experience trying to get videos to loop consistently using a basic iframe. I am not interacting with the API via code. I simply have an iframe with autoplay=1,mute=1,loop=1. I've tried using stand-alone videos and I've tried playlists (with list=[ID],listType=playlist) and I keep running into the same problem. Sometimes the player will loop the video and sometimes it will not. Every time I think I have it figured out and I'm ready to deploy the app, I test it again and the video fails to loop.

Windows 10

Chrome 71.0.3578.98

Angular 6.0.3

Dan Rullo
  • 323
  • 2
  • 10

1 Answers1

1

You can choose any of these options:

  • Check my answer where I described how you can set your URL for create a playlist (using a single videoId) and simulate a loop.

  • Use the YouTube iframe Player API for set your video and (once the video ended), call the playVideo() function for play the current video = hence, creating a loop.

This is the code: - unfortunately, you can't see it working here, but, you can see the working jsfiddle1

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// Variables of the divs (where the YouTube iframe will load):
var player;

function onYouTubeIframeAPIReady() {

  // Div player:
  player = new YT.Player('player', {
    height: '360',
    width: '640',
    videoId: 'xPCZEoGJi_4',
    playerVars: {
      'autoplay': 1,
      'loop': 1,
      'mute': 1
    },
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });

}

// 5. The API calls this function when the player's state changes.
function onPlayerStateChange(event) {

  // When the video ends, it will play again.
  // See: https://developers.google.com/youtube/iframe_api_reference?hl=en#Events
  if (event.data == YT.PlayerState.ENDED) {
    player.playVideo();
  }
}

// Div "player" - The API will call this function when the video player is ready.
function onPlayerReady(event) {
  event.target.playVideo();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="player"></div>

1 If the video (once has loaded) hasn't play, you have to play manually the video - this is due some kind of restrictions that jsfiddle has.

Mauricio Arias Olave
  • 2,259
  • 4
  • 25
  • 70