IndexSizeError在使用JS的视频元素上衰减声音时引起

IndexSizeError caused when Fading in the sound on a Video Element using JS

本文关键字:声音 衰减 元素 JS 的视频 IndexSizeError      更新时间:2023-09-26

我得到以下错误

music.js:31 Uncaught IndexSizeError:未能在"HTMLMediaElement"上设置"volume"属性:提供的音量(1)超出范围[0,1]。

下面显示了我的代码。我已经为这个例子提供了一个远程mp3文件,当你运行这个片段时可以使用。

我想弄清楚的是,我有一个条件集,当音量达到1时,清除间隔并停止。

提供的音量(1)在范围[0,1]之外,这对我来说没有意义,因为音量是1。

有什么建议吗?

window.onload = function playSound() {
    var currentSound;
// I have a div called "page"
    var soundcv = window.document.body;
    // Set the point in playback that fadeout begins. This is for a 2 second fade out.
// This only works for one sound for simplicity's sake
    function playSound(sound) {
        if (currentSound == null) {
            var audio = window.document.createElement('video');
            audio.setAttribute('id','audio1');
            audio.src = sound;
            audio.id = 'video';
            soundcv.appendChild(audio);
            currentSound = audio;
        }
        currentSound.volume = 0;
        currentSound.play();
    }
// This isn't a real audio file URL - replace it with one of your own
    playSound('http://dl.last.fm/static/1458674990/114531092/eaba95c9c6e959558078b8f4eaab169211205de80b3e194238a5469e9a0c5c84/Somewhere+off+Jazz+Street+-+Collateral+Damage.mp3');
    function fadeIn() {
        if (currentSound.volume === 1) {
            clearInterval(timer);
            return;
        }
        currentSound.volume += 0.005;
    }
    var timer = setInterval(fadeIn, 200);
};

TL;DR:

你应该通过这样设置音量来修复它:

currentSound.volume = Math.min(currentSound.volume + 0.005, 1);


因为JS(和其他语言)使用IEEE 754来存储浮点数,这会出现精度错误。示例:0.1 + 0.2 === 0.30000000000000004

在间隔通话中,您可以使用0.005增加当前音量。当你接近1时,你会得到0.9950000000000008。下一个迭代是:0.9950000000000008 + 0.005 === 1.0000000000000007

尝试:for(var i = 0, a = 0; i < 200; i++){console.log(a += 0.005)}

这里的问题是控制台的消息,其中1没有给出指数部分(.0000000000000007

==对于任何看到相同错误的人,请阅读此===

你必须得到这个错误,HTML5播放器的音量只能设置在0到1[0,1]之间。

为了实现从0到1的运行,假设您有一个范围输入,如下所示:

<input id="Volume" type="range" onmouseup="SetVolume(this.value)" min="0" max="10" step="1">
   function SetVolume(val){
    var newVolume=val / 10;
    // when is 1 it will give 0.1 and so on up to 0.9 
    //next push will be 1 and it stops.
    currentSound.volume=newVolume;
    });