Youtube player api with loop
Asked Answered
B

7

23

I am struggling with setting up the loop for youtube videos using youtube player api.

The problem is that the video is not running under a loop.

Here is my code

var tag = document.createElement('script');

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


      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',

          playerVars: {
            'controls': 0,           
            'showinfo': 0,
            'rel': 0,
            'loop': 1

          },
          videoId: 'qzZuBWMnS08',
          events: {
            'onReady': onPlayerReady,
           // 'onStateChange': onPlayerStateChange
          }
        });
      }
function onPlayerReady(event) {
        //  event.target.setLoop(true);
        event.target.playVideo();
      }

The loop:1 doesn't seem to be working.Also is there any way to remove the share and video title from the top of the video.

Thanks in advance.

Badoglio answered 16/10, 2013 at 18:16 Comment(0)
I
56

If the video isn't changing, you can just do

onStateChange: 
    function(e) {
        if (e.data === YT.PlayerState.ENDED) {
            player.playVideo(); 
        }
    }

This will prevent unnecisarily reloading the video

Iconoduly answered 7/5, 2015 at 15:43 Comment(3)
+1 for the approach above because it will immediately play the video avoiding the quick flash of black screen that happens when one uses the "&playlist=VIDEO_ID" suggested by GoogleMelva
Great solution. Just FYI you can also play the video like this e.target.playVideo() to make it a bit more dynamic.Legible
If for some reason (i.e using external module ) you can't get access to the variable YT and its properties YT.PlayerState.ENDED is (at the time of writing this) 0, so you can substitute this for 0 .Miceli
M
19

This is what I have used for the API IFrame video loop. I noticed that you must include "playlist:VIDEO_ID" parameter. and it works. This is my example

<script>
  // 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);

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

  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
      height: '390',
      width: '640',
      videoId: 'VIDEO_ID',
      playerVars: {
        playlist: 'VIDEO_ID',
        loop: 1
      }
    });
  }
</script>
Marcelinomarcell answered 4/9, 2016 at 19:17 Comment(1)
Experimenting with this on Android, I found that this only works if you call the javascript loadPlaylist() method, instead of loadVideo(). As a side-effect, this causes the YouTube web UI to show the playlist control, which allows the user to see a pop-up list of videos in the playlist. In the case where looping is wanted on a single video, this is an unwanted side-effect, as the UX feels clunky with a single-video playlist.Katabasis
C
12

As stated in the documentation, you need to set the playlist parameter to the video ID in order for loop to work.

You'll be wanting the showinfo parameter to hide the title etc.

Compo answered 16/10, 2013 at 23:11 Comment(2)
The problem of this method is that it loads the same video again as a new video.Photofinishing
Missed this. I can't check now, but wouldn't that be a non-issue as the browser should have the video cached/loaded from the previous playback?Compo
U
8

Try this in your onPlayerStateChange, in some sort of way Youtube wants you to put in the videoID again.

onStateChange: function(e){
    var id = 'qzZuBWMnS08';

    if(e.data === YT.PlayerState.ENDED){
        player.loadVideoById(id);
    }
}
Undersurface answered 20/11, 2013 at 20:6 Comment(0)
T
3

I got this to work to give me loop video with super low volume set for playing video. You can mute by changing volume from 2 to 0.

Also make sure your video is added to a playlist. Apparently that is an issue now. And use video id in both playlist and videoid areas in the code.

Im sure i have extra steps or redundant steps as im no coder.

I just know this works.

    <div id="player">
<script>
      // 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');
      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
      // 3. This function creates an <iframe> (and YouTube player)
      //    after the API code downloads.
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '315',
          width: '600',
          videoId: 'DrrH-YTvVVc',
          playerVars: {
          playlist: 'DrrH-YTvVVc',
          loop: 1      }       ,
   events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }
      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
           event.target.setVolume(2);
       event.target.playVideo();
      }

      // 5. The API calls this function when the player's state changes.
      //    The function indicates that when playing a video (state=1),
      //    the player should play for six seconds and then stop.
      var done = true;
      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.ENDED) {
    //      setTimeout(stopVideo, 6000);
                  player.playVideo();
        }
           event.target.setVolume(2);
      }
</script></div>
Troll answered 16/4, 2018 at 18:55 Comment(0)
A
2

Working loop example (02-2019)

<div id="ytplayer">
<script>
  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 player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
      width: '640',
      height: '360',

          // 1. Video_Id
          videoId: 'AfAwsdbj04I',

      playerVars: { 
          autoplay: 1,
          loop: 1,
          controls: 0,
          rel: 0,
          modestbranding: 1,

          // 2. Playlist_Id (don't forget "PL")
          playlist: 'PLxWQS97ZR2-_c2eqKxSHxEu7v462-qnYM'

      },
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }
  function onPlayerReady(event) {
    event.target.setVolume(80);
    event.target.playVideo();
 //  player.mute();
  }
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.ENDED) {
      player.seekTo(0);
      player.playVideo();
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
</script>
</div>
Andrea answered 11/2, 2019 at 15:29 Comment(1)
Hello, and thanks for sharing an answer. In general, people are looking for explanations, not code. Maybe try expanding your answer with some idea of why your suggestion works and/or what they were doing wrong to begin with.Annihilation
C
0

Since the html5 player, we can just right click on the video => play in loop.

From script, to replay at the end of the video:

document.getElementsByClassName('video-stream html5-main-video')[0].loop = true

Loop 1.66 seconds between two time points:

const video = document.getElementsByClassName('video-stream html5-main-video')[0]

/* Loop markers in seconds */
let start = 54.34, end = 56

/* Seek to time in seconds */
function seek(time){
  video.loop = true
  video.currentTime = time
  video.play()
}

/* Loop between start and end */
function loop(e){
  if (e.target.currentTime > end){
    seek(start)
  }
}

/* Will loop for 1.66s */
video.addEventListener("timeupdate", loop, false)

/* Seek to 54.34s */
seek(start)

/* Abort the loop */
// video.removeEventListener("timeupdate", loop, false)

/* New loop */
// start = 14; end = 15; seek(start)

Media events list

HTMLMediaElement reference

Contumelious answered 6/8, 2019 at 14:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.