leohxj
9/30/2013 - 4:58 AM

创建Youtube播放器

创建Youtube播放器

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>HTML5 MediaElement</title>
    <link rel="stylesheet" href="style/normalize.css">
    <link rel="stylesheet" href="style/style-youtube.css">
</head>
<body>
    <div class="video-wrapper">
        <div class="video-bg">
            <img src="image/Pokemon-bg.jpg" alt="">
        </div>
        <div class="video-loading">
            <img src="image/loading.gif" alt="">
        </div>
    </div>

<div class="video">
    <div id="player"></div>
</div>

<script src="javascript/mediaelement/jquery.js"></script>
<script src="javascript/mediaelement/mediaelement.js"></script>
<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        playerVars: {
            'controls': 0,
            'showinfo': 0,
            'modestbranding': 1,
            'rel': 0,
            'vq': 'hd720'
        },
      width: '970px',
      height: '1032px',
      videoId: 'ncnF05k5oWs',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    console.log('===video will play');
    event.target.setPlaybackQuality('hd720');
    event.target.playVideo();
    // console.log(event.target.getPlaybackQuality());
    // console.log(event.target.getPlayerState());
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    // if (event.data == YT.PlayerState.PLAYING && !done) {
    //   setTimeout(stopVideo, 6000);
    //   done = true;
    // }
    if (event.data == YT.PlayerState.PLAYING) {
        console.log('===PLAYING===');
        $('.video-loading, .video-bg').css('opacity', '0');
        console.log(event.target.getPlaybackQuality());
        if (event.target.getPlaybackQuality() != 'hd720') {
            event.target.setPlaybackQuality('hd720');
        }
    }
    if (event.data == YT.PlayerState.BUFFERING) {
        console.log('===BUFFERING===');
    }
    // if (event.data == YT.PlayerState.ENDED) {
    //     console.log('===ENDED===');
    //     $('.video-loading, .video-bg').css('opacity', '1');
    // }
  }
  function stopVideo() {
    player.stopVideo();
  }
</script>

</body>
</html>