javascript 如何初始化YouTube的API播放器?

rbl8hiat  于 12个月前  发布在  Java
关注(0)|答案(1)|浏览(103)

我正试图实现一个自定义控件的背景视频(倒带5秒,降低播放速度)。我想使用YouTube链接作为视频源,我不希望任何YouTube信息显示,也没有默认控件。
我试过使用iframe和video标签,但是iframe不能改变速度,也不能倒带(从我收集的信息来看),video标签不能使用YT链接。
通过这样做,我从youtube得到错误代码M2 sXarBf-_A4NpgU(基本上告诉我视频无法加载,但它没有说明原因,我在控制台上没有得到任何错误)。

let player

function onYouTubeIframeAPIReady() {
  console.log("api loaded")
  player = new YT.Player("myvid", {
    videoID: "QPjHCAHfjoU",
    host: 'https://www.youtube.com',
    playerVars: {
      autoplay: 1,
      muted: 1,
      controls: 0,
      origin: 'http://127.0.0.1:3000/client/main.html'
    }
  })
}
#myvid {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100vw;
  height: 100vh;
  transform: translate(-50%, -50%);
}

.video-background {
  background: #000;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: -99;
}

.video-foreground,
.video-background iframe {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100vw;
  height: 100vh;
  transform: translate(-50%, -50%);
}
<div class="video-background">
  <div class="video-foreground">
    <div id="myvid"></div>
  </div>
</div>
eimct9ow

eimct9ow1#

but the iframe can't change the speed nor rewind我相信你可以使用iframe来实现这一点,你可能已经错过了添加函数来做同样的事情。我相信你提供的代码只有这么多。
创建一个自定义视频播放器并添加JavaScript函数用于倒带和速度控制。对于. eg HTML

<div class="video-background">
    <div class="video-foreground">
        <div id="myvid"></div>
    </div>
    <div class="custom-controls">
        <button id="rewindButton">Rewind 5s</button>
        <button id="reduceSpeedButton">Reduce Speed</button>
    </div>
</div>

JS

let player;

function onYouTubeIframeAPIReady() {
    player = new YT.Player("myvid", {
        videoId: "QPjHCAHfjoU",
        playerVars: {
            autoplay: 1,
            mute: 1,
            controls: 0,
        },
        events: {
            onReady: onPlayerReady,
        },
    });
}

function onPlayerReady(event) {
    // Define custom control actions
    document.getElementById("rewindButton").addEventListener("click", rewindVideo);
    document.getElementById("reduceSpeedButton").addEventListener("click", reduceSpeed);
}

function rewindVideo() {
    const currentTime = player.getCurrentTime();
    player.seekTo(currentTime - 5, true);
}

function reduceSpeed() {
    const currentPlaybackRate = player.getPlaybackRate();
    player.setPlaybackRate(currentPlaybackRate - 0.25); // You can adjust the speed reduction factor
}

相关问题