带有使用视频标签的自定义取消静音按钮的 Vimeo 视频

Vimeo video with a custom unmute button using a video tag

目前我正在使用 html5 <video> 标签从 Vimeo direct link 自动播放页面加载视频,这会在页面和海报上快速加载视频属性也有助于感知加载时间:

<video id="video" poster="abc.jpeg?$staticlink$" playsinline muted>
      <source type="video/mp4" src="https://player.vimeo.com/external/408636.hd.mp4?s=1552e499fb1e3aa2bf881c2ae762aa23988b5d&profile_id=175">
</video>

现在我想要一种使用页面上的按钮取消静音的方法,我决定这样做我现在必须使用 Vimeo API player.js。请参阅下面的代码。我现在遇到的问题是 iframe 加载缓慢,vimeo API 似乎没有海报属性。

  <html>
    <div id="video" width="100%" height="100%"></div>
    <button class="volume">VOLUME ON</button>
  </html>

  <script>
    var volBtn = document.querySelector('.volume')

    var options = {
      url: "https://vimeo.com/123/456",
      loop: true,
      autoplay: true,
      background: true
    };

    var videoPlayer = new Vimeo.Player('video', options);

    volBtn.addEventListener('click', () => {
      videoPlayer.setVolume(1);
    })
  </script>

有没有更好的方法来做到这一点,让我们同时拥有视频标签速度和 iframe 取消静音的能力?我是否遗漏了视频或 iframe 标签中明显的内容?我可以在 Vimeo API 中使用视频标签吗?

不需要为此使用 player.js。就这么简单:

const volBtn = document.querySelector('.volume')
const video = document.querySelector('#video')
volBtn.addEventListener('click', function() { videoEl.muted = false })

另请注意,在 HTMLMediaElement API 的帮助下设置静音视频的音量会使其静音。所以这个

volBtn.addEventListener('click', function() { videoEl.volume = 1 })

不会像您预期的那样工作。但这会

volBtn.addEventListener('click', function() {
 videoEl.muted = false
 videoEl.volume = 1
})

您不需要使用 Vimeo API, you can use the HTMLMediaElement.muted 属性 而是:

// NOTE: cache the "video" element to prevent unnecessary re-selecting of the same object
const video = document.querySelector("#video");
document
  // select the volume button
  .querySelector(".volume")
  // bind a click event
  .addEventListener("click", () =>
    // unmute the video
    video.muted = false
  );

如果您想切换静音功能,请改用 event handler

() =>
  // toggle mute feature
  video.muted = !video.muted;

祝你好运。