I'm not able to get the correct video duration/length (in seconds) of a loaded/cued video via the getDuration() method of the YouTube Player API; the same method, however, returns a valid value once the video starts playing! Wondering how YouTube is able to show the valid duration of a loaded/cued video.
When I load this HTML page with a 15 second video clip, I get the following debug output:
state = 5 duration = -0.000025
When I hit the Play button, I get the following debug output:
state = 3 duration = 15,
Would greatly appreciate a solution or a workaround. Loading, and immediately playing and pausing the player would be not my favorite method.
<html>
<head>
<script type="text/javascript">
var videoId;
videoId = 'http://www.youtube.com/v/4TSJhIZmL0A'; // bbc
// videoId = 'http://www.youtube.com/v/ezwyHNs_W_A'; // physics
function $(id) {
return document.getElementById(id);
}
</script>
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("swfobject", "2.1");
</script>
</head>
<body>
<table>
<tr><td>
<div id="player">
You need Flash player 8+ and JavaScript enabled to view this video.
</div>
<script>
var ytplayer;
function myOnPlayerStateChange(state) {
switch(state) {
case 1: // playing
$("out").innerHTML += " playing";
break;
case 2: // paused
$("out").innerHTML += " paused";
break;
case 0: // ended
$("out").innerHTML += " ended";
break;
case -1: // unstarted
case 3: // buffering
case 5: // cued
$("out").innerHTML += " state = " + state;
break;
default: // unknown
$("out").innerHTML += " state = " + state;
break;
}
$("out").innerHTML += " duration = " + ytplayer.getDuration() + ",";
}
function myOnPlayerError(errorCode) {
$("out").innerHTML += " Error occurred: " + errorCode;
}
function onYouTubePlayerReady(playerId) {
ytplayer = ytplayer || $(playerId);
ytplayer.addEventListener("onStateChange", "myOnPlayerStateChange");
ytplayer.addEventListener("onError", "myOnPlayerError");
}
var params = { allowScriptAccess: "always", bgcolor: "#cccccc" };
var atts = { };
swfobject.embedSWF(videoId + "?border=0&enablejsapi=1&playerapiid=" + 'player', 'player', 425, 344, "8", null, null, params, atts);
</script>
</td></tr>
</table>
<div id="out"></div>
<div id="err"></div>
</body>
</html>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…