Web Audio API:性能问题?

Web Audio API: performance problems?

我这里有一个小编钟器。它一次产生多个泛音,并在每个泛音上使用可变增益来产生丰富的铃声。我调用一个函数来按顺序播放一系列这些。但是如果我快速按下按钮几次,声音输出就会停止,就好像 运行 内存不足:

https://codepen.io/ophello/pen/OJVRMQe

function ding(freq) {
    var toneGen = new AudioContext()
    var duration = 15
    var T = toneGen.currentTime
    var overtones = [1,2.76,5.4,8.93,13.34,18.64]
    overtones.forEach(function(overtone,i) {
        var osc = toneGen.createOscillator()
        osc.type = "sine"
        var freqVal = freq * overtone
        if (freqVal <= 22050) {
            osc.frequency.value = freq * overtone
            var envelope = toneGen.createGain()
            osc.connect(envelope)
            envelope.gain.setValueAtTime(0.1/Math.pow((i+1),5), T)
            envelope.gain.exponentialRampToValueAtTime(0.00001, T + duration)
            envelope.connect(toneGen.destination)
            osc.start(T)
            osc.stop(T + duration)
        }
    })
}

var hzValues = [216, 288, 324, 405, 432, 648]

$("#b1").mousedown(() => { 
    hzValues.forEach((thisHz,i) => { 
        setTimeout(() => { ding(thisHz) }, 100 * i); 
    })
})

为什么按几下就停止工作了?我在这里遗漏了一些重要的东西吗?我不知道在控制台的哪个位置可以找到与此相关的任何问题。这是内存问题吗?

感谢上面的 dandavis,我通过添加超时功能使它工作:

setTimeout(toneGen.close.bind(toneGen), duration*1000);

更新:通过将音频上下文移到主函数之外进行了改进!