1

使用 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>
4

1 回答 1

0

我看到你在代码中做的一些有问题的事情。

一般来说,您不应该在代码中重复调用loadPlaylist()++ 。我建议在开始时调用+一次,然后每当你想播放“随机”视频时,只需调用. 因为播放列表已经随机播放,所以下一个视频实际上是随机的。setShuffle()playVideo()loadPlaylist()setShuffle()nextVideo()

于 2013-02-04T23:04:13.550 回答