How to fade a sound

Hello everyone !

I made a search on the forum about how to fade out a sound. There was a topic in 2015, but it is not accessible anymore.

I know this function : hypeDocument.getElementById(‘audio’).volume=.1; which is used to control the volume, but do you know how I could achieve fading a sound with JS (for example when the user click a button) ?

Thank you !

Nicolas from Belgium

I guess you would use a setInterval function to change the time by increments.

You can also tween it using GSAP for instance.

Yeah I would do something like this: http://stackoverflow.com/a/7942472 and link it to a button @haloniko

// 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);
1 Like

Example: https://photics.com/games/annoyed-tomatoes/

1 Like

wow, really cool library.

Thank you to everyone for answering ! Your help is precious :slight_smile: and I hope I will have the opportunity to help back, although I am clearly less skilled with these.

But now, I am facing another sound problem (I am not expert with JS). This function is working fine on desktop and mobile :

var myAudio = document.getElementById(“sound”);
myAudio.play();

But this function is not working on mobile, only on desktop :

hypeDocument.getElementById(‘sound’).volume=.15;

Could you help me to understand how to make it works ? Basically, I want to dim the sound when one is clicking something.

Thank you to !