首页 > 解决方案 > 使用 vanilla javascript 淡出音频

问题描述

如何使用 vanilla js(无 jquery)淡出音频元素?我查看了这个论坛上的许多其他问题,但它们似乎都过于复杂或使用 jquery。我在下面写了这段代码。但是,我收到以下错误:“未捕获的 DOMException:无法在 'HTMLMediaElement' 上设置 'volume' 属性:提供的音量 (-7.52870e-16) 超出范围 [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();

    });

标签: javascripthtml5-audiopannellum

解决方案


假设vol当前值为 0.005。您的代码当前设置的方式if (vol > 0)true,因此您将减去 0.01,得到vol-0.005 的值。由于现在小于零,因此在尝试将音量设置为该级别时会出现错误。

解决方法是在测试vol -= 0.01 之前调用if(vol > 0)。这样,如果vol降至 0 以下,您将不会尝试将音量设置为无效级别。


推荐阅读