【问题标题】:YouTube Player API - Seek and then playYouTube Player API - 搜索然后播放
【发布时间】:2018-11-10 11:48:24
【问题描述】:

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

【问题讨论】:

  • 我想我已经深入了解了。如果您使用 .stopVideo() 则 .seekTo() 在那之后不起作用 - 如果您使用 .pauseVideo() 然后 .seekTo() 它会按预期工作

标签: javascript youtube


【解决方案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>

【讨论】:

  • 当视频暂停/停止时 - 单击“搜索”按钮确实会搜索到正确的点,但我还需要在不按播放器上的播放按钮的情况下播放视频
  • 当视频停止并单击搜索按钮时,您可以检查视频持续时间是否等于视频当前时间,它等于所有视频的第一个已播放而不是之后将搜索视频。 if(player.getCurrentTime() == player.getDuration()) { player.playVideo(); }
猜你喜欢
  • 1970-01-01
  • 2014-02-02
  • 2013-06-09
  • 2015-12-31
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多