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++) {
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);
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?
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.
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
Reference it to a variable i.e:
var myAudioCtx = new AudioContext();
Then destroy by calling
myAudioCtx.close();
That's it.