diff --git a/packages/superdough/audioContext.mjs b/packages/superdough/audioContext.mjs index 1c708e814..6a701d9ad 100644 --- a/packages/superdough/audioContext.mjs +++ b/packages/superdough/audioContext.mjs @@ -19,6 +19,9 @@ export const setAudioContext = (context) => { // Existing nodes in the node pool contain references to the previous AudioContext, // so all the nodes in the pool must be cleared when we set a new AudioContext. clearNodePool(); + if (audioContext && audioContext.state !== 'closed') { + audioContext.close(); + } audioContext = context; return audioContext; }; diff --git a/packages/superdough/helpers.mjs b/packages/superdough/helpers.mjs index 07199aff6..7431bf530 100644 --- a/packages/superdough/helpers.mjs +++ b/packages/superdough/helpers.mjs @@ -6,8 +6,8 @@ import { clamp, nanFallback, midiToFreq, noteToMidi } from './util.mjs'; export const noises = ['pink', 'white', 'brown', 'crackle']; -export function gainNode(value) { - const node = getAudioContext().createGain(); +export function gainNode(value, audioContext = getAudioContext()) { + const node = audioContext.createGain(); node.gain.value = value; return node; } @@ -374,7 +374,7 @@ export function webAudioTimeout(audioContext, onComplete, startTime, stopTime) { // Certain browsers requires audio nodes to be connected in order for their onended events // to fire, so we _mute it_ and then connect it to the destination - const zeroGain = gainNode(0); + const zeroGain = gainNode(0, audioContext); zeroGain.connect(audioContext.destination); constantNode.connect(zeroGain);