audiocontext 采样率在被读取 8 次后返回 null

audiocontext Samplerate returning null after being read 8 times

我制作了一个产生鼓声的函数,但是在被调用 4 次后它停止工作并出现错误:

TypeError: null is not an object (evaluating 'audioCtx.sampleRate') Showing in the console.

这个函数有什么问题? 我的代码是:

drum = function(){
    var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    var frameCount = audioCtx.sampleRate/20
    var myArrayBuffer = audioCtx.createBuffer(1, frameCount, audioCtx.sampleRate);
    var nowBuffering = myArrayBuffer.getChannelData(0);
    for (var i = 0; i < frameCount; i++) {
        nowBuffering[i] =Math.sin(i**(1/1.8)/4)
    }

    var source = audioCtx.createBufferSource();
    source.buffer = myArrayBuffer; source.connect(audioCtx.destination);
    source.start();
}

您的 audioCtx 作业应该移到 drum() 之外,因为它每次都会被调用,最终会抛出异常,因为您不能在文档中创建超过 6 个音频上下文。

事实上,重复使用 AudioContext 的一个实例并不是好的解决方案,因为它可能会导致内存泄漏。

当浏览器空闲时(当您切换到另一个 iOS 应用程序时),这种长期存在的 AudioContext 实例会被 Safari 终止。再次打开 Safari 后,AudioContext 实例将不再可用。

正确的解决方案是每次都创建新的上下文并在不再需要时关闭它。

使用这种方法,不会对 AudioContext 应用浏览器限制。

const drum = () => {
  const audioCtx = new (window.AudioContext || window.webkitAudioContext)()
  // your stuff here…

  // Return cleanup function and call it when needed
  return () => {
    // Cleanup to prevent memory leaks
    audioCtx
      .close()
      .catch(() => {
        console.log('Closing AudioContext failed')
      })
  }
}