AudioContext 在函数外部定义时不产生声音

AudioContext produces no sound when defined outside of a function

根据文档,您应该每页只调用一次 AudioContext。

当我尝试正确使用它并在函数外调用它时,没有声音产生。上下文变量已定义并填充,控制台中不会抛出任何错误,只是不会发出声音。

当我在每个 'onClick' 事件调用的函数中调用它时,它最初是有效的,但是我在第 6 次调用它时不出所料地得到了一个错误,因为我已经达到了我可以调用的次数限制它。

var context = new AudioContext; //when defined here, no sound is produced

function playChord() {
    var context = new AudioContext; //when defined here, sound is produced (only 6 times)

    var time = 0.05;
    var frequencies = [...];
    frequencies.forEach(function(frequency) {
        var oscillator = context.createOscillator();
        var gain = context.createGain();

        gain.gain.setValueAtTime(0, audioContext.currentTime);
        gain.gain.linearRampToValueAtTime(1, time);
        gain.gain.linearRampToValueAtTime(0, time + 60*0.25);

        oscillator.frequency.value = frequency;
        oscillator.connect(gain);
        gain.connect(context.destination);

        oscillator.start(...);
        oscillator.stop(...);
    });
};

为什么仅仅移动上下文变量的实例化就会阻止我的浏览器 (chrome) 发出声音?

发现了我自己的问题。不出所料,这是一个愚蠢的错误。问题出在这一行

gain.gain.linearRampToValueAtTime(1, time);

相对于 context.currentTime,我没有一次将增益设置为 1。

在函数内部定义 AudioContext 时它能正常工作的原因是 'currentTime' 从 0 开始计数,并且足够接近仍然影响相关振荡器。

当它被移出函数时,时间远远超过了 linearRamptoValueAtTime() 会影响任何东西的范围。加上context.currentTime就OK了:)

gain.gain.linearRampToValueAtTime(1, context.currentTime + time);
gain.gain.linearRampToValueAtTime(0, context.currentTime + time + 0.25);