Youtube API播放下一个视频if else声明

时间:2013-01-28 16:37:49

标签: iframe youtube-api

使用iframe youtube API我想这个if else语句在给定所选数字的情况下播放此播放列表中的某个随机视频。截至目前,它似乎给了我一些重复的视频,而不是基于生成的随机数。

  <script type="text/javascript">
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player(
    'player', {
      height: '390',
      width: '640',
      playerVars: {},
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange,
        'nextVideo': nextVideo,
      }
    });
  }
  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {   
  player.loadPlaylist({
                 list: 'mozart',
                 listType:'search',
               })   
  event.target.playVideo();
  } 

  function nextVideo() {
  var num = Math.round(Math.random() * 4);
  console.log(num);

  if (num >= 2) {
  player.nextVideo();
  player.loadPlaylist({
                 list: '90s rap',
                 listType: 'search',
               })   
   player.setShuffle(true);
   player.playVideo();

  }

  else if (num < 2) {
    player.nextVideo();
   player.loadPlaylist({
                 list: 'mozart',
                 listType:'search',
               })   
 player.setShuffle(true);
 player.playVideo();
  }
  else {}

  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),

  function onPlayerStateChange(event) {

  }
  function stopVideo() {
    player.stopVideo();
  }
</script>

这是html

<a href="javascript:nextVideo()" id="next">Next</a>

1 个答案:

答案 0 :(得分:0)

我在你的代码中看到了一些可疑的事情。

通常,您不应在代码中反复调用loadPlaylist() + setShuffle() + playVideo()。我建议您在开始时拨打loadPlaylist() + setShuffle(),然后每当您想播放“随机”视频时,只需致电nextVideo()。由于播放列表已经改组,下一个视频实际上是随机的。