Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript slowly decrease volume of audio element

audio element is playing with volume:

audio.setVolume(.20)

At a certain point I want to fade out the volume, rather than have it cut abruptly, so in essence I want

audio.setVolume(.15)
audio.setVolume(.10)
audio.setVolume(.05)
audio.setVolume(.03)
audio.setVolume(.01)

but there needs to be some very brief delay in between these changes so they are audible and I get my fade out effect. What is the proper way to do this?

thanks!

like image 401
istan Avatar asked Dec 03 '22 00:12

istan


1 Answers

You could use a setInterval():

// Initial volume of 0.20
// Make sure it's a multiple of 0.05
var vol = 0.20;
var interval = 200; // 200ms interval

var fadeout = setInterval(
  function() {
    // Reduce volume by 0.05 as long as it is above 0
    // This works as long as you start with a multiple of 0.05!
    if (vol > 0) {
      vol -= 0.05;
      audio.setVolume(vol);
    }
    else {
      // Stop the setInterval when 0 is reached
      clearInterval(fadeout);
    }
  }, interval);
like image 195
Michael Berkowski Avatar answered Dec 20 '22 03:12

Michael Berkowski