【问题标题】:No video sound if removing attribute muted on html element video如果删除 html 元素视频上静音的属性,则没有视频声音
【发布时间】:2019-09-10 21:37:38
【问题描述】:

我使用 HTML video 元素。作为source,我使用带有声音的.mp4 视频。在我的video 元素上有一些属性。默认我使用属性muted,所以没有声音。使用一些 JavaScript,我通过单击按钮添加或删除属性 muted。所以这很有效,当我检查我的标记并单击按钮时,我可以看到属性 muted 将如何添加或删除(查看下面的我的 sn-p)。

我的问题是,删除它时,没有声音。如果我在笔记本电脑的视频播放器中启动视频文件或直接在浏览器中打开它,我可以听到声音。由于许多帖子,应该可以使用此解决方案切换声音。我不知道为什么只有在我的video 元素中使用它并添加/删除属性muted 时它才没有声音。有什么想法吗?

const $ctx = $('.video');
const $video = $ctx.find('.video__video');
const $toggleSound = $ctx.find('.video__toggle-sound');

$toggleSound.click(this.handleVideoSound.bind(this));

function handleVideoSound() {
  const attr = $video.attr('muted');

  if (typeof attr !== typeof undefined && attr !== false) {
    $video.removeAttr('muted');
  } else {
    $video.attr('muted', '');
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="video">
  <video class="video__video" autoplay loop muted playsinline poster="/assets/img/video-poster.png">
    <source src="/assets/video/video.mp4" type="video/mp4">
  </video>
  <button class="video__toggle-sound">Toggle video sound</button>
</div>

【问题讨论】:

  • 您的视频属性中有mutet 而不是muted?我猜只是一个错字问题:-)
  • @GrahamRitchie 这是 sn-p 中的错字,在我的代码中是 muted。但下面的答案奏效了!

标签: javascript html attributes html5-video


【解决方案1】:

用下面的代码替换你的 handleVideoSound 方法

function handleVideoSound() {
   const attr = $video.prop("muted");
   $video.prop("muted", !attr);
}

希望对您有所帮助。下面是工作代码 sn-p。

const $ctx = $(".video");
const $video = $ctx.find(".video__video");
const $toggleSound = $ctx.find(".video__toggle-sound");
$toggleSound.click(this.handleVideoSound.bind(this));

function handleVideoSound() {
    const attr = $video.prop("muted");
    $video.prop("muted", !attr);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="video">
<video class="video__video" autoplay loop muted playsinline poster="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg">
<source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", type="video/mp4" />
</video>
<button class="video__toggle-sound">Toggle video sound</button>
</div>

【讨论】:

  • 我知道 prop 是较新的 attr 方式,但在此代码中也做了同样的猜测,它删除并添加了我的属性 muted。但是为什么我现在在使用 prop 时有声音,到目前为止我还不清楚。
  • 欢迎!您可以通过此link 了解属性和属性之间的区别
猜你喜欢
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-12
  • 2015-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多