问题
I wrote this stupid toy using the YouTube API. Basically it just starts multiple copies of a video at different randomized times. That worked great for like a year. But today I noticed that the randomized start times no longer work, it just starts all of the videos at t=0 (tested on multiple browsers/OSes/computers).
Any idea what's wrong? I'm just passing a random number to the start parameter. Seems simple.
Here's my code. The key part is in the add
function, where the start
parameter is set in playerVars
.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Flockas</title>
</head>
<body>
<button id="pause">Pause Flockas</button>
<button id="add">Add One Flocka</button>
<button id="remove">Remove One Flocka</button>
<p>
<div id="flockas"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
var flockas = [];
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onPlayerReady(event) {
event.target.playVideo();
}
function add() {
var start = Math.random() * 60;
$("#flockas").append('<div id="flocka' + flockas.length + '" class="flocka"></div>');
flockas.push(new YT.Player('flocka' + flockas.length, {
height: '105',
width: '140',
videoId: 'yOc-MXGuKgs',
playerVars: {
autoplay: 1,
loop: 1,
playlist: 'yOc-MXGuKgs',
start: start
},
events: {
'onReady': onPlayerReady
}
}));
}
function remove() {
var divs = $(".flocka");
$(divs[divs.length - 1]).remove();
flockas.splice(flockas.length - 1)
}
function pause() {
var pauseEl = $("#pause");
if (pauseEl.html() === "Pause Flockas") {
for (var i = 0; i < flockas.length; i++) {
flockas[i].pauseVideo();
}
pauseEl.html("Play Flockas");
} else {
for (var i = 0; i < flockas.length; i++) {
flockas[i].playVideo();
}
pauseEl.html("Pause Flockas");
}
}
function onYouTubeIframeAPIReady() {
for (var i = 0; i < 5; i++) {
add();
}
}
$("#add").click(add);
$("#remove").click(remove);
$("#pause").click(pause);
</script>
</body>
</html>
Like I said above, this worked fine when I originally made it, and I only very recently noticed that it doesn't work.
回答1:
The start parameter still works. The problem is, that you compute a wrong value for it: wrong type. Maybe it has been changed: Supplying a valid INTEGER value works. (If fractions are allowed, then not all are valid.)
For example, if you want a value between 0 and 200 then use:
var maxVal = 200;
var startVal = Math.ceil((Math.random() * maxVal));
来源:https://stackoverflow.com/questions/23821157/setting-video-start-time-with-the-youtube-api-start-playervars-option-used-t