4

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!

istan
  • 1,349
  • 3
  • 21
  • 36

3 Answers3

11

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);
Carson
  • 6,105
  • 2
  • 37
  • 45
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • You don't need to set a multiple of 0.05 if you test ` if (vol >= 0.0.5)`. Or am I missing something ? – Titou Apr 20 '22 at 14:43
  • @Titou Doing some archaeology? Yes you're correct I think. Any starting volume would work if the condition is `>= 0.05` and the subtractor is exactly 0.05 so it reaches zero. Would there be additional floating point weirdness? I don't know. There might already have been. – Michael Berkowski Apr 20 '22 at 17:37
7

I would wrap the setTimeout inside of the function, as well as the options. Regarding the factor, 0.01 will be a safe value to decrease without you having to know or adjust the initial value.

function fadeVolume(volume, callback)
{
    var factor  = 0.01,
        speed   = 50;
    if (volume > factor)
    {
        setTimeout(function(){
            fadeVolume((audio.volume -= factor), callback);         
        }, speed);
    } else {
        (typeof(callback) !== 'function') || callback();
    }
}
fadeVolume(audio.volume, function(){
    console.log('fade complete');
});

Once the fade is complete, it will fire a callback that you can use to play the next song.

xmarcos
  • 3,298
  • 2
  • 20
  • 27
0

You can use this mouse key event too.

audio.on('keydown', function() {
// and here keep increasing or decreasing the volume, untill keyUp
})

As being viewed, its jQuery! You can use it for your work. Also, the audio tag is for the div, that contains the audio tag!

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103