Failed to construct 'AudioContext': number of hardware contexts reached maximum

后端 未结 5 1761
名媛妹妹
名媛妹妹 2021-02-07 03:49

Is there a way to remove an AudioContext after I\'ve created it?

var analyzers = [];
var contexts = [];

try {
   for(var i = 0; i<20; i++) {
            


        
相关标签:
5条回答
  • 2021-02-07 04:01

    Close it before each click. If you use the timer to delay the closing, there will be an exception of incomplete playback, especially when switching files.

    const audioPlay = (() => {
      let context = null;
      return async () => {
        if (context) context.close();
        context = new AudioContext();
        const source = context.createBufferSource();
        source.buffer = await fetch('./2.mp3')
          .then(res => res.arrayBuffer())
          .then(arrayBuffer => context.decodeAudioData(arrayBuffer));
        source.connect(context.destination);
        source.start();
      };
    })();
    
    document.querySelector('#add').addEventListener('click', audioPlay);
    

    Not recommended

     setTimeout(() => { context.close();}, 400);
    
    0 讨论(0)
  • 2021-02-07 04:10

    You should really only have one AudioContext in the page.

    From the docs: "In most use cases, only a single AudioContext is used per document."

    I can't really think of a reason why you'd ever need more than one. Is there a specific issue you've run into that caused you to create multiple contexts?

    0 讨论(0)
  • 2021-02-07 04:12

    I was working on a media player widget which broke on Chrome (but not Firefox) as soon as more than five were embedded in a single page.

    I discovered that you can create a single AudioContext and store it globally, then have each instance just use the shared AudioContext. It seems to work no differently - you can attach multiple buffers and multiple destinations and the audio all gets mixed together.

    This might require more effort if you're using it for timing, but for playback of one or more audio streams generated on-the-fly with JS code, sharing a single AudioContext works fine.

    0 讨论(0)
  • 2021-02-07 04:19

    AudioContext.close() will release the hardware of the context, but check that it is available only for recent versions of chrome and firefox. Not available for IE aparently. Check the documentation: https://developer.mozilla.org/en-US/docs/Web/API/AudioContext/close

    0 讨论(0)
  • 2021-02-07 04:25

    Reference it to a variable i.e:
    var myAudioCtx = new AudioContext();
    Then destroy by calling
    myAudioCtx.close();
    That's it.

    0 讨论(0)
提交回复
热议问题