【问题标题】:How to apply a fade effect in HTML5 mute button如何在 HTML5 静音按钮中应用淡入淡出效果
【发布时间】:2016-10-03 19:29:32
【问题描述】:

我有一个静音按钮,可以简单地将 HTML5 音频对象静音。它确实使轨道静音,但我喜欢添加淡入/淡出效果。 我通过添加audio.animate({volume: 0}, 2000); 进行了尝试,但它不起作用。

有什么想法吗?

提前致谢!

audio = new Audio();
audio.src = "http://myst729.qiniudn.com/within-temptation_pale.mp3"
audio.play();

$(".mute").on("click tap", function(){
	if (audio.muted) {
            audio.animate({volume: 1}, 2000);
            audio.muted = false;
            $(this).text("mute");

        } else {
            audio.muted = true;
            audio.animate({volume: 0}, 2000);
            $(this).text("unmute");
        }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="mute">mute</button>

【问题讨论】:

标签: javascript jquery css html audio


【解决方案1】:

audio 对象应该是一个 JQuery 对象才能使用 JQuery .animate() 函数。您可以通过将audio.animate 更改为$(audio).animate 来做到这一点。

此外,audio.muted = ... 语句会立即关闭/打开音乐,因此您不会听到动画。

一个工作示例:

audio = new Audio();
audio.src = "http://myst729.qiniudn.com/within-temptation_pale.mp3"
audio.play();

$(".mute").on("click tap", function() {
  var $btn = $(this);
  
  var muted = audio.muted;
  if (muted) audio.muted = false; // It cannot be animated if it's muted
  
  $btn.prop('disabled', true); // Optional
  $(audio).animate({volume: muted ? 1 : 0}, 2000, function() {
    audio.muted = !muted;
    $btn.text(muted ? "mute" : "unmute");
    $btn.prop('disabled', false); // Optional
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="mute">mute</button>

【讨论】:

  • 如果audio.muted = true 显然无法为音频设置动画,因此取消静音动画无法正常工作。我通过解决这个问题改进了我的答案;)
猜你喜欢
  • 2010-10-17
  • 2020-12-28
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 2011-03-05
  • 2011-10-16
  • 1970-01-01
相关资源
最近更新 更多