Note that there are some explanatory texts on larger screens.

plurals
  1. POYouTube Player API: How to get duration of a loaded/cued video without playing it?
    text
    copied!<p>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.</p> <p>When I load this HTML page with a 15 second video clip, I get the following debug output:</p> <p><strong>state = 5 duration = -0.000025</strong> </p> <p>When I hit the Play button, I get the following debug output:</p> <p><strong>state = 3 duration = 15,</strong></p> <p>Would greatly appreciate a solution or a workaround. Loading, and immediately playing and pausing the player would be not my favorite method.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; 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); } &lt;/script&gt; &lt;script src="http://www.google.com/jsapi"&gt;&lt;/script&gt; &lt;script&gt; google.load("swfobject", "2.1"); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;table&gt; &lt;tr&gt;&lt;td&gt; &lt;div id="player"&gt; You need Flash player 8+ and JavaScript enabled to view this video. &lt;/div&gt; &lt;script&gt; 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&amp;amp;enablejsapi=1&amp;amp;playerapiid=" + 'player', 'player', 425, 344, "8", null, null, params, atts); &lt;/script&gt; &lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;div id="out"&gt;&lt;/div&gt; &lt;div id="err"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload