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

前端 未结 5 1144
你的背包
你的背包 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: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]();
    
    }
    

提交回复
热议问题