javascript - 使用 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();
});
解决方案
假设vol
当前值为 0.005。您的代码当前设置的方式if (vol > 0)
是true
,因此您将减去 0.01,得到vol
-0.005 的值。由于现在小于零,因此在尝试将音量设置为该级别时会出现错误。
解决方法是在测试vol -= 0.01
之前调用if(vol > 0)
。这样,如果vol
降至 0 以下,您将不会尝试将音量设置为无效级别。
推荐阅读
- android - 捕获仅发送空对象的 Xamarin CollectionView 选择是怎么回事?
- hash - 获取上传到 IPFS 的文件夹中单个文件的 HASH
- flutter - 如何使用构造函数在有状态小部件中传递数据?
- azure - 对 AzureAD 的错误请求
- java - javafx gradle插件有java10兼容版本吗?
- c# - 使用 .net core 将 Html 转换为纯文本
- npm - Webpack 插件:如何在构建时读取插件使用者的文件?
- javascript - 画布:在整个画布上创建半透明覆盖,除了一个窗口
- javascript - 正则表达式从开始查找字符串
- huggingface-transformers - 减少 XLTransformers 的输出层大小