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!