0

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>
DannyBoy
  • 434
  • 5
  • 21

1 Answers1

3

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>
Duncan Lukkenaer
  • 12,050
  • 13
  • 64
  • 97
  • Apparently audio cannot be animated if `audio.muted = true`, so the unmute-animation didn't work properly. I have improved my answer by fixing this ;) – Duncan Lukkenaer Oct 03 '16 at 20:12