YouTube Player API-搜寻然后播放

时间:2018-11-10 11:48:24

标签: javascript youtube

尝试将launch/async与YouTube Player API一起使用时遇到问题。我第一次设置.seekTo()时,视频将正确搜索到该值(例如4秒),然后播放[我没有发出.seekTo()的声音]。当我第二次致电.playVideo()时,视频停止播放,并且视频从头开始播放。我希望能够从搜索位置重新开始播放视频。

1 个答案:

答案 0 :(得分:1)

<!DOCTYPE html>
<html>
<head>
<scriptm src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
  <div id="player"></div>
<div>
  <button id="btnSeek" data-seek="30.7">Seek 30</button>
  <button id="btnSeek" data-seek="60">Seek 60</button>
  <button id="btnSeek" data-seek="90">Seek 90</button>
  <button id="btnSeek" data-seek="180">Seek 180</button>
</div>

<script>
$.getScript('//www.youtube.com/iframe_api');
 var player;
 function onYouTubePlayerAPIReady() {
     player = new YT.Player('player', {
       height: '390',
       width: '640',
       videoId: '-HjpL-Ns6_A',
         playerVars: { 'start': 159, 'autoplay': 1, 'controls': 1, 'showinfo': 0, 'rel': 0 },
       events: {
         'onReady': onPlayerReady,
         'onStateChange': onPlayerStateChange,
       } 
     });         
 }
 var done = false;
 function onPlayerStateChange(evt) 
 {
  if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
 }
 function onPlayerReady(evt) {

    // doesn't work here
    // player.seekTo(30);  

     // lets make ure we have a function
     //alert("typeof(player.SeekTo) = " + typeof(player.seekTo));
 }
 function stopVideo() {
    player.stopVideo();
  }

 $(function() {

$(document).on('click', '#btnSeek', function() {
   if(player.getCurrentTime() == player.getDuration())
   {
     player.playVideo();
   }
    player.seekTo($(this).data('seek'), true);
});
});
</script>
</body>