Garbage Collection and Audio: What I Clean Up After Every Sound
Short answer: Stop every sound source you start, and disconnect its nodes when it ends. The leak that is easiest to miss is an oscillator that was started and never stopped, especially a slow one used for wobble. It keeps running for as long as the page is open, heard or not.
const osc = audioCtx.createOscillator();
const gain = audioCtx.createGain();
osc.connect(gain).connect(audioCtx.destination);
osc.start(now);
osc.stop(now + duration); // always schedule the stop
osc.onended = () => { // then let go of everything
osc.disconnect();
gain.disconnect();
};
Why it matters for a page like mine
A demo that plays for ten seconds can leave everything lying around. My app is meant to stay open all day. Every time two shapes touch, it builds a few nodes, plays them for a second or two and is done with them. Over a working day that is many thousands of small sounds. If each one leaves something behind, the page gets slower by evening.
What I'm sure of
A source that is still running costs something, even at zero volume. An oscillator doesn't stop because you can no longer hear it. If you fade the gain to nothing and walk away, the oscillator behind it is still producing a signal.
The ones I forgot were the slow oscillators that make a sound wobble. They don't feel like sounds, so it is easy to start one and never stop it.
What I'm not sure of
Whether a node that has finished playing gets freed by itself if you leave it connected. The specification has rules about what keeps a node alive, and I have read that browsers have not always behaved the same way. I didn't manage to pin it down. So I disconnect everything when a sound ends and don't have to find out.
So treat "disconnect every node" as my habit and not as a law.
The rest of my routine
- Every short sound stops its source and disconnects itself when it ends.
- When a shape leaves the screen, its long sound is taken apart: sources stopped, wobble stopped, nodes disconnected.
- All the noise-based sounds share one buffer of noise. I don't create a new one each time.
How to check your own page
Leave it running for an hour with the browser's task manager open and watch the memory figure. If it climbs steadily and never comes down, something is being left behind.
Try it: leave Ocean open for a working day. It is free and starts in one click, with no account.
Open Ocean, free