Search code examples
javascripthtml5-audiopannellum

Fade out audio using vanilla javascript


How can I fade out an audio element using vanilla js (no jquery)? I have looked at the numerous other questions on this forum but they all seem overly complicated or use jquery. I have written this code below. However, I get the following error: "Uncaught DOMException: Failed to set the 'volume' property on 'HTMLMediaElement': The volume provided (-7.52870e-16) is outside the range [0, 1]."

        viewer.on('mouseup', function(event) {

        var mouseDownSound = document.getElementById("mouseDownSound");
        mouseDownSound.volume = 1;
        var vol = mouseDownSound.volume;
        function fadeOut() { 
            setInterval(
              function() {
                if (vol > 0) {
                  vol -= 0.01;
                  mouseDownSound.volume = vol;
                }
                else {
                  clearInterval(fadeOut);
                }
              }, 2);
        }
        fadeOut();

    });

Solution

  • Let's say vol currently has a value of 0.005. The way your code is currently set up, if (vol > 0) is true, so you will then subtract 0.01, giving vol a value of -0.005. Since that is now less than zero, you will get an error when attempting to set the volume to that level.

    The fix is to call vol -= 0.01 before you test if(vol > 0). That way, if vol drops below 0 you won't be attempting to set the volume to an invalid level.