我无法通过 YouTube Player API 的 getDuration() 方法获得加载/提示视频的正确视频持续时间/长度(以秒为单位);然而,一旦视频开始播放,同样的方法会返回一个有效值!想知道 YouTube 如何能够显示加载/提示视频的有效持续时间。
当我用 15 秒的视频剪辑加载这个 HTML 页面时,我得到以下调试输出:
状态 = 5 持续时间 = -0.000025
当我点击播放按钮时,我得到以下调试输出:
状态 = 3 持续时间 = 15,
将不胜感激解决方案或解决方法。加载、立即播放和暂停播放器不是我最喜欢的方法。
<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>