如何在HTML5静音按钮中应用淡入淡出效果

问题描述:

我有一个静音按钮,只是将HTML5音频对象静音。它确实使曲目静音,但我喜欢添加淡入/淡出效果。 我尝试了加入audio.animate({volume: 0}, 2000);但它不工作。如何在HTML5静音按钮中应用淡入淡出效果

有什么想法?

提前致谢!

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

 
$(".mute").on("click tap", function(){ 
 
\t 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>

+0

把每一件事在animate函数 –

+0

@KarthikeyanSekar这样'audio.animate({体积:1,audio.muted = FALSE},2000) ;'? – DannyBoy

+1

[HTML5

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>

+0

显然音频不能如果'audio.muted = true',请动画,所以unmute-animation无法正常工作。通过解决这个问题,我改进了我的答案;) –