youtubeyoutube-apiyoutube-javascript-api

Youtube API seekTo() in float seconds


Does the Youtube API seekTo function accept time in float or in frames? Can you drill down up to two decimal places?


Solution

  • Yes, the API accepts seekTo time in float perfectly; it will advance to the closest keyframe before your float, whatever that may be. Here's a demonstration:

     
            var tag = document.createElement('script');
            tag.src = "http://www.youtube.com/player_api";
            var firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
            var player;
            function onYouTubePlayerAPIReady() {
                player = new YT.Player('player', {
                    height: '390',
                    width: '640',
                    videoId: 'u1zgFlCw8Aw'
                });
            }
            $(window).load(function(){
                jQuery('#seek').click(function(){
                    player.seekTo(parseFloat($("#seekto").val()));
                    return false;
                });
            });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <div id="player"></div><br/>
    Seek to <input type="text" id="seekto" value="25.5"/> seconds<br/>
    <a href="#" id="seek">Seek</a>

    Seeking to a frame is a little trickier of a beast, as different videos have different fps rates. Since you can't get the fps via the API (unless there's a method I don't know?), it would be too difficult to try to write a wrapper that could convert the frame you want to seek to into a float. If they are your videos, though, and you know the fps rate, it would be pretty trivial.