0

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

    });
  • 200 seconds (-0.01 per 2 secs) are more than 3 minutes, have you waited at least half minute for something to happen? – tevemadar Jun 04 '21 at 17:34
  • thank you, I have made the change, however I have updated the post because now I'm getting an error message: myscript.js:669 Uncaught DOMException: Failed to set the 'volume' property on 'HTMLMediaElement': The volume provided (-7.52870e-16) is outside the range [0, 1]. –  Jun 04 '21 at 17:43
  • Try calling `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. – kmoser Jun 04 '21 at 17:43
  • thank you! it works and doesn't throw an error message. I don't understand why it works though, I would think that the 'vol -= 0.01' would need to be after the test. –  Jun 04 '21 at 17:46
  • See my answer for a description of why this works. – kmoser Jun 04 '21 at 17:51

1 Answers1

0

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.

kmoser
  • 8,780
  • 3
  • 24
  • 40