0

The first video plays, but not the next video in my list. I have copied the initial code from the YouTube API example. Also the idea of using onPlayerStateChange(event) from this SO answer.

The first video plays fine. Using Firebug, I can also see that it goes into the playnextvideo() function. However, the next video doesn't play. I also tried adding

 player.playVideo() 

in the last line of that function, but I get an error saying "player.playVideo() is not a function". Below is my entire <body> section. There is no other script in this page.

<div id="container">
<div id="content">
    <div class="fixedwidthlower">
    <?php
        require 'dbconn.inc'; //database connection code
        echo "<div id=\"SongList\"><ul id = \"songs\">";
        $list = explode(" ", $_POST['playlist']);
        $hlist = array();
        for($i=0; $i<count($list); $i++){
            $sql = "SELECT * FROM songs where aikey = " . $list[$i] . ";";
            $result = $conn->query($sql);
            $row = $result->fetch_assoc();
            if ($i==0)
                $liclass = " class=\"active\"";
             else
                $liclass = "";
            echo "<li" . $liclass . "><a href=\"" . $row["URL"] . "\">" . $row["Song"] . " (" . substr($row["URL"], stripos($row["URL"], "=") + 1) . ")</a></li>";
            $hlist[] = substr($row["URL"], stripos($row["URL"], "=") + 1);
        }
        echo "</ul></div>";
        echo "<div id=\"Player\">";
        for($i=0; $i<count($hlist); $i++){
            echo $hlist[$i] . " ";
        } // This loop puts the raw videoids into the Player Div
          // which are then read by the first line in javascript below
          // Example: "usNsCeOV4GM 8pPvNqOb6RA cwqhdRs4jyA XcATvu5f9vE WANNqr-vcx0 t-iJ47in9YQ OMOGaugKpzs l3LFML_pxlY mLDDxfFKd9Y 9Z4rmlyuH-s "
        echo "</div>";
        $conn->close();
    ?>
</div>
</div>
<script type="text/javascript">
        var videolist = document.getElementById("Player").innerHTML.split(" ");
        var i =0;
        var video = videolist[i];
        function playnextvideo(){
            i++;
            video = videolist[i];
            playmyvideo();
            player.playVideo();
        }
        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() {
            playmyvideo();
        }
        function playmyvideo() {
                player = new YT.Player('Player', {
                height: '390',
                width: '640',
                videoId: video,
                    events: {
                    'onReady': onPlayerReady,
                    'onStateChange': onPlayerStateChange
                }
            });
        }
        function onPlayerReady(event) {
            event.target.playVideo();
        }
        function onPlayerStateChange(event) {
            if (event.data === 0) {
                playnextvideo();
            }
        }
        console.log(i);
        console.log(video);
    </script>

The php code is probably not relevant, but I have shown it for completeness. I have not included the CSS because it is probably not relevant (there are no display:none divs as I have seen causing problems in other questions). If you want a link to the page this is on, I can provide that too...

Thanx for your help!

Community
  • 1
  • 1
Chiwda
  • 1,233
  • 7
  • 30
  • 52

1 Answers1

1

You need to revise your implementation and use loadPlaylist or cuePlaylist function as it will perfectly solve your issue without implementing too much complicated codes.

Using loadPlaylist lets you load a specified playList and plays it. In the sample below I specified a list of video ids that I want to play in the onPlayerReady event.

(you can try to run the code below in jsFiddle)

<div id="player"></div>
<script>
  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 onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  function onPlayerReady(event) {
    event.target.loadPlaylist(['RB-RcX5DS5A','QtXby3twMmI']);
  }
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      done = true;
    }
  }
 function stopVideo() {
    player.stopVideo();
 }
</script>
goblin
  • 1,513
  • 13
  • 13
  • I'll try this, but this doesn't help the big picture. I want to be able to play videos from other sites. Thus, I will switch to another function that instantiates a different player using a different API say. Vimeo when a Vimeo video comes up. – Chiwda Dec 23 '15 at 03:25
  • Thanx! It works and so I have accepted your answer. However, I realize now that my architecture is wrong. I have to put the loop outside the YouTube API (and the other APIs). Duh! – Chiwda Dec 23 '15 at 05:44