istan
istan

Reputation: 1359

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!

Upvotes: 5

Views: 14687

Answers (3)

Michael Berkowski
Michael Berkowski

Reputation: 270647

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);

Upvotes: 11

Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

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!

Upvotes: 0

xmarcos
xmarcos

Reputation: 3368

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.

Upvotes: 7

Related Questions