YouTube API无法持续加载

时间:2019-01-07 17:25:52

标签: javascript jquery youtube youtube-api

对于我所工作的大学,我正在尝试在网页的横幅中获取一个YouTube视频以自动播放。 API并非每次都正确加载。我不确定该如何解决。

我尝试过:

  • 仅当DOM准备就绪时,才将youtube API脚本添加到。

  • 将代码放在页面顶部和底部。

  • 检查播放器对象是否正确创建,以及是否尝试重新创建它(据我所知)会破坏API。

如果我剥离所有页面并仅显示横幅,则视频加载的频率会更高,但仍不是100%。

在这里,我在通过YouTube API加载视频的页面上提供了脚本。

更新: 通过登录控制台,可以看出播放器对象尚未完全初始化。 如果创建不正确,则对象的打印结果如下:

Y {b: null, a: null, h: null, closure_uid_165988549: 1, g: 1, …}

这是正确完成的时间:

Y {b: Wa, a: iframe#ytplayer, h: div#ytplayer, closure_uid_16195269: 1, g: 1, …}

我错了,因为找不到视频ID。每次调用函数之前都会设置视频,因此这不应该成为问题。

<div id="ytplayer"></div>

  <script>
    defer(function() {if(window.mobile === true) { $('#ytplayer').remove(); }});
     var ready;
    // Replace the 'ytplayer' element with an <iframe> and
    // YouTube player after the API code downloads.
    var player;
    // var videoId = 'ZCESafUzSRo';
  function onYouTubeIframeAPIReady() {
      checkFunction();
    }

    function checkFunction() {
      console.log("checkFunction called");
      setYTready(ready);
    }
    function setYTready(ready) {
      console.log("setYT ready called");
      ready = true;
      mtuPlayerCreate(player);
    }

    function mtuPlayerCreate(player) {
      console.log("mtu create called");



      if((player == undefined) && ( document.getElementById("play-yt") != null)) {
    console.log("Creating player");
      player = new YT.Player('ytplayer', {
        height: '52.65%',
        width: '100%',
        playerVars: {
          'controls': 0,
          'showinfo': 0,
          'rel': 0,
          'iv_load_policy': 3
        },
        videoId: videoId,
        events: {
          'onReady': onPlayerReady,
          // Removing the following if loop shouldn't be enabled
          onStateChange: 
          function(e){
            if (e.data === YT.PlayerState.ENDED) {
              player.playVideo(); 
            }
          }
        }
      });

    }
    console.log("player redo below");
    console.log(player);
      if(player.A == false) {
      //setTimeout(function() {location.reload();}, 2000); 
    } else {
      return;
    }
  }


    function onPlayerReady(event) { /* configuring default playing and mute settings */
      console.log("on ready has been called")
      var autoPlay = 1;
      var autoMute = 1;
      if(autoPlay === 1) { event.target.playVideo(); }
      if(document.getElementById('play-yt') && autoPlay === 1) { document.getElementById('play-yt').className = 'pause'; }else if(document.getElementById('play-yt')) { document.getElementById('play-yt').className = 'play'; }
      if(autoMute === 1) { event.target.mute(); }
      if(document.getElementById('mute-yt') && autoMute === 1) { document.getElementById('mute-yt').className = 'mute'; }else if(document.getElementById('mute-yt')) { document.getElementById('mute-yt').className = 'loud'; }
      if(document.getElementById('yt-yt')) { document.getElementById('yt-yt').className = ''; }
    }

    window.onload = function() { /* this handles what happens when the player and its buttons are clicked on */

            document.getElementsByClassName('media-black')[0].onclick=function(e) { 
        if(e.target.id !== 'yt-yt' && e.target.id !== 'mute-yt') {
          if(player.getPlayerState() === -1 || player.getPlayerState() === 2  || player.getPlayerState() === 5) {  
            player.playVideo(); 
            if(document.getElementById('play-yt')) { document.getElementById('play-yt').className = 'pause'; }
            if (window._gaq) _gaq.push(['_trackEvent', 'Wide Video', 'Played', window.location.href]);
          }else{
            player.pauseVideo(); 
            if(document.getElementById('play-yt')) { document.getElementById('play-yt').className = 'play'; }
            if (window._gaq) _gaq.push(['_trackEvent', 'Wide Video', 'Paused', window.location.href]);
          }
        }
        else if(e.target.id === 'yt-yt' && e.target.id !== 'mute-yt') {
          window.open('http://www.youtube.com/watch?v=' + videoId, '_blank');
          player.pauseVideo();
          if(document.getElementById('play-yt') && document.getElementById('play-yt').className === 'pause') { document.getElementById('play-yt').className = 'play'; }
          if (window._gaq) _gaq.push(['_trackEvent', 'Wide Video', 'Went to YouTube', window.location.href]);
        }else{
          if(player.isMuted() || player.getVolume() === 0) { player.unMute(); player.setVolume(100); document.getElementById('mute-yt').className = 'loud'; }else{ player.mute(); document.getElementById('mute-yt').className = 'mute'; }
          if (window._gaq) _gaq.push(['_trackEvent', 'Wide Video', 'Sound Adjusted', window.location.href]);
        }
      };



    }

    //
    //This could be improved, test if it's mobile and load if not instead of loading and then removing if mobile
    //
    // Load the IFrame Player API code asynchronously.
    document.addEventListener("DOMContentLoaded", function(event) { 
      console.log("dom ready!");
    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  });
  </script> 
</div>

它需要做的是:

  1. 加载API
  2. 使用给定的视频ID加载播放器对象
  3. 将iframe添加到正确的位置
  4. 自动播放视频。

每次页面加载时都需要这样做。

1 个答案:

答案 0 :(得分:0)

我不确定为什么要以这种方式加载YouTube iframe播放器,但是,我通过修改代码来实现了jsfiddle,并且YouTube播放器iframe可以正常工作。

这些是我所做的修改-您可以在修改后的代码中找到更多注释:

  • 我评论了mtuPlayerCreate行-您是否要添加另一个YouTube Iframe?
  • 添加onPlayerStateChange函数以设置HTML元素的功能-能够控制iframe-“播放/暂停,(取消)静音视频”
  • controls的值为0,我将其设置为1,以通过单击HTML元素检查其是否正确控制了YouTube iframe。

这是jsfiddle代码:

// No need for replace the elemnt - YouTube Iframe Player will load in this object and HTML element:
var player;

// This is your videoId "you had it commented".
// it was the video is not available:
//var videoId = 'ZCESafUzSRo';

// Video: "Microsoft Windows Mixed Reality update | October 2018" - by Microsoft Hololens.
var videoId = '00vnln25HBg';

// Check whether iframe is mute.
var isUnMuted = false;

// Here, the YouTube Player API will build the iframe in the "ytplayer" HTML element
// and in the "player" variable.
function onYouTubeIframeAPIReady() {
  player = new YT.Player('ytplayer', {
    height: '52.65%',
    width: '100%',
    playerVars: {
      'controls': 1, 
      'showinfo': 1,
      'rel': 0,
      'iv_load_policy': 3,
      'autoplay': 1,
      'loop': 1,
    },
    videoId: videoId,
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });

  // After loading the iframe, set the "playVideo" onclick event on "playButton" anchor element.
  document.getElementById('play-yt').onclick = function() {
    player.playVideo();
  };

  // Thanks to this answer, here you can check the status of "mute" - I culdn't make it work, in the "onPlayerStateChange" function though.
  // Source: https://stackoverflow.com/a/36436765/4092887
  document.getElementById('mute-yt').innerHTML = 'MUTE';
  document.getElementById('mute-yt').onclick = function() {
    player.mute();
  };

  document.getElementById('yt-yt').innerHTML = 'UNMUTE';
  document.getElementById('yt-yt').onclick = function() {
    player.unMute();
  };

}

function checkFunction() {
  console.log("checkFunction called");
  setYTready(ready);
}

function setYTready(ready) {
  console.log("setYT ready called");
  // Not sure what you're doing here = do you want load another youtube iframe?
  //mtuPlayerCreate(player);
}

function mtuPlayerCreate(player) {
  console.log("mtu create called");



  if ((player == undefined) && (document.getElementById("play-yt") != null)) {


  }
  console.log("player redo below");
  console.log(player);
  if (player.A == false) {
    //setTimeout(function() {location.reload();}, 2000); 
  } else {
    return;
  }
}

/* configuring default playing and mute settings */
/* You only need set here the following line: */
function onPlayerReady(event) {
  event.target.playVideo();
}

/* this handles what happens when the player and its buttons are clicked on */
/* You can do it in this way instead: */
function onPlayerStateChange(e) {
  // Removing the following if loop shouldn't be enabled.
  // This is for emulate "loop" functionality.
  if (e.data === YT.PlayerState.ENDED) {
    player.playVideo();
  }

  // If the video is PLAYING, set the onclick element for pause the video.
  // Once the "playButton" is clicked, the video will be paused.
  if (e.data == YT.PlayerState.PLAYING) {
    document.getElementById('play-yt').innerHTML = 'PAUSE';
    document.getElementById('play-yt').onclick = function() {
      player.pauseVideo();
    };
  }

  // If the video is PAUSED, set the onclick element for pause the video.
  // Once the "playButton" is clicked, the video will resume the video = continue playing the video.
  if (e.data == YT.PlayerState.PAUSED) {
    document.getElementById('play-yt').innerHTML = 'PLAY';
    document.getElementById('play-yt').onclick = function() {
      player.playVideo();
    };
  }

}

//
//This could be improved, test if it's mobile and load if not instead of loading and then removing if mobile
//
// Load the IFrame Player API code asynchronously.
document.addEventListener("DOMContentLoaded", function(event) {
  console.log("dom ready!");
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="ytplayer"></div>

<p>
  <div>
    <span>Control your Youtube Iframe Player:</span>
  </div>

  <div id="play-yt">PLAY</div>
  <div id="mute-yt">MUTE</div>
  <div id="yt-yt">UNMUTE</div>
</p>