在使用YouTube Player API的getDuration()方法获取已加载/缓存视频的正确持续时间(以秒为单位)时,我无法获得正确的值;但是,一旦视频开始播放,相同的方法就会返回有效值!想知道YouTube是如何显示已加载/缓存视频的有效持续时间。
当我加载一个15秒的视频剪辑的HTML页面时,我得到以下调试输出:
state = 5 duration = -0.000025
当我点击播放按钮时,我得到以下调试输出:
state = 3 duration = 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>