YouTube Player API: How to get duration of a loaded/cued video without playing it?

前端 未结 5 1064
你的背包
你的背包 2020-12-02 19:16

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,

相关标签:
5条回答
  • 2020-12-02 19:45

    Here one that converts the time over for you.

        <script type="text/javascript">
    function youtubeFeedCallback(json){
    
    var totalSec = json["data"]["duration"];
    var hours = parseInt( totalSec / 3600 ) % 24;
    var minutes = parseInt( totalSec / 60 ) % 60;
    var seconds = totalSec % 60;
    
    var result = (hours < 1 ? "" : hours + ":") + (minutes < 1 ? "0" : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);
    
    document.write(result);
    }
    </script>
    <script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/LzPWWpKlvqQ?v=2&alt=jsonc&callback=youtubeFeedCallback&prettyprint=true"></script>
    
    0 讨论(0)
  • 2020-12-02 19:46

    "Loading, and immediately playing and pausing the player would be not my favorite method."

    I don't think there is any other method.

    In my case it works well, even for a satellite internet user.

    Here is my code :

    // I set youtube player-ready event to a variable for irrelevant reasons
    function onYouTubePlayerReady(playerid) { 
        youtube_player_ready;
    }
    youtube_player_ready = function(playerid) {
    
        // load video
        document.getElementById(playerid).cueVideoById(yt_video_id);
        // mute video
        document.getElementById(playerid).mute();
        // play video to get meta data
        document.getElementById(playerid).playVideo();
    
        yt_get_duration[index] = function(){
            // if duration is available
            if (document.getElementById(playerid).getDuration() > 0) {
                // pause video
                document.getElementById(playerid).pauseVideo();
                // unmute
                document.getElementById(playerid).unMute();
                // save duration
                video_duration = document.getElementById(playerid).getDuration();
    
            }
            // else keep trying
            else {
                setTimeout(yt_get_duration[index], 150)
            }
        }
        // get duration
        yt_get_duration[index]();
    
    }
    
    0 讨论(0)
  • 2020-12-02 20:07

    Solution 1

    You can use YouTube Data API to access most of the information about the video, including duration:

    <script type="text/javascript">
        function youtubeFeedCallback(json){
            document.write(json["data"]["duration"] + " second(s)");
        }
    </script>
    <script type="text/javascript" src="http://gdata.youtube.com/feeds/api/videos/4TSJhIZmL0A?v=2&alt=jsonc&callback=youtubeFeedCallback&prettyprint=true"></script>
    

    Demo here

    When using jQuery you can use $.getJSON() to make things easier.

    Solution 2

    Seems like YouTube JavaScript API v3 allows you to get the correct duration inside the onYouTubePlayerReady() event. All you need to do is pass &version=3 when calling swfobject.embedSWF() method.

    Demo here

    0 讨论(0)
  • 2020-12-02 20:07

    Using jQuery

    var youTubeURL = 'http://gdata.youtube.com/feeds/api/videos/oHg5SJYRHA0?v=2&alt=json';
    var json = (function () {
        $.ajax({
            'async': false,
            'global': false,
            'url': youTubeURL,
            'dataType': "jsonp", // necessary for IE9
            crossDomain: true,
            'success': function (data) {
                var duration = data.entry.media$group.yt$duration.seconds;
            }
        });
    })();
    
    0 讨论(0)
  • 2020-12-02 20:11

    Following these steps:
    1. Get youtube video id
    2. Use youtube API to get duration (ISO 8601 duration)
    3. Convert ISO 8601 duration to time

    Using Jquery:

    // convert ISO 8601 duration
    function covtime(youtube_time){
      array = youtube_time.match(/(\d+)(?=[MHS])/ig)||[]; 
        var formatted = array.map(function(item){
            if(item.length<2) return '0'+item;
            return item;
        }).join(':');
        return formatted;
    }
    
    // print video duration
    $('iframe').each(function(i) {
        var ifr = $(this);
        var regExp = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
        var match = ifr.attr('src').match(regExp);  // get youtube video id
        if (match && match[2].length == 11) {
            var youtubeUrl = "https://www.googleapis.com/youtube/v3/videos?id=" + match[2] 
            + "&key=AIzaSyDYwPzLevXauI-kTSVXTLroLyHEONuF9Rw&part=snippet,contentDetails";
            $.ajax({
                async: false,
                type: 'GET',
                url: youtubeUrl,
                success: function(data) {
                  var youtube_time = data.items[0].contentDetails.duration;
                  var duration = covtime(youtube_time); 
                  if(ifr.next().is('.time')) {
                    ifr.next().html(duration);
                  }
                }
            });
        }
    });
    
    0 讨论(0)
提交回复
热议问题