News for hackers. Stuff that matters.
Re:Building a musical instrument with the Web Audio API by bambax on Friday May 13, 2022 @09:26AM (#31367299)
> Sine and triangle were a bit more subdued but if you don't fade the sound out properly, it makes a really unpleasant kind of cutting sound due to how your ear reacts when a wave gets cut off.

The clicking sound happens when a wave is stopped when not at 0. You do need to fade the oscillator down before stopping it.

> As I was figuring everything out, I was experimenting with making new AudioContext for every note because I was trying to fade out the sound, but then I kept realizing that after 50 notes, the app would stop working. Fifty is apparently the limit for the browser, so it's better to just make one AudioContext for the entire app.

Yeah the reason the app would stop working when doing things this way is, just because the gain of the oscillator is zero, and the oscillator therefore not audible, it's still there! If you put the gain back up you can hear it again. You can't just fade out and be done with it.

So the appropriate approach (not explicitly explained in the article IMHO) is to

1/ set the gain to zero:

    g.gain.setTargetAtTime(0, context.currentTime, 0.1)
2/ then kill the oscillator with stop(), so that it doesn't consume resources anymore:

    o.stop(context.currentTime + 0.5)
(g being the gain and o the oscillator, and context the AudioContext).

Note: "then" means the two actions need to happen one after the other, and that is decided by parameters of the two functions; the functions themselves aren't chained and can be written in any order.

There are no comments on this comment yet.