代码之家  ›  专栏  ›  技术社区  ›  user7951676

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

  •  4
  • user7951676  · 技术社区  · 8 年前

    TypeError:null不是对象(正在评估“audioCtx.sampleRate”)

    我的代码是:

    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();
    }
    
    2 回复  |  直到 7 年前
        1
  •  12
  •   dpren    8 年前

    你的 audioCtx drum() ,因为它每次都会被调用,最终会引发异常,因为在一个文档中创建的音频上下文不能超过6个。

        2
  •  -1
  •   poky    5 年前

    事实上,重用AudioContext的一个实例并不是一个好的解决方案,因为它有潜在的内存泄漏。

    当浏览器空闲时(当您切换到另一个iOS应用程序时),Safari会杀死这样一个长期存在的AudioContext实例。一旦Safari再次打开,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')
          })
      }
    }