DannyBoy DannyBoy - 2 months ago 22
CSS Question

How to apply a fade effect in HTML5 mute button

I have a mute button that simply mute a HTML5 audio object. It does mute the track but I like to add a fade in/out effect.
I tried it by adding

audio.animate({volume: 0}, 2000);
but its not working.

Any idea?

Thank in advance!



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>




Answer

The audio object should be a JQuery-object in order to use the JQuery .animate() function. You can do that by changing audio.animate to $(audio).animate.

Also the audio.muted = ... statements turn off/on the music instantly, so you won't hear the animations.

A working example:

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>