Web Audio API clicking sound when stopping oscillator

708 Views Asked by At

When using the web audio API to make an oscillator, Im always hearing that clicking sound when stopping it. Ive searched arround, but none of the solutions would work for me. I tried all implementations from How can I avoid this 'clicking' sound when I stop playing a sound? and more

I read one solution would be to wait for the next zero amplitude value and then stop playing immediately. Is there a way to do so with the web audio api?

I was thinking about switching to Tone.Js for my project, because the sounds play without the clicking. How do they solve the problem?

Im surprised that there is no build in solution for that

1

There are 1 best solutions below

0
On BEST ANSWER

The best way to get rid of the click is to fade out the signal. Here's a small example (untested):

let c = new AudioContext();
let s = new OscillatorNode(c);
let g = new GainNode(c);
s.connect(g).connect(c.destination);
g.gain.setValueAtTime(1, c.currentTime);
s.start();
// Let's stop the oscillator in 5 sec.
let stopTime = c.currentTime + 5;
s.stop(stopTime);
// Fade out the signal.  Fade out starts 0.25 sec before we stop.
// Then we linearly ramp down to 0 at stopTime
g.gain.setValueAtTime(1, stopTime - 0.25);
g.gain.linearRamptToValueAtTime(0, stopTime);

There's more than one way to fade out the signal. Another way is:

g.gain.setTargetAtTime(0, stopTime - 0.25, .025);

This starts fading out 0.25 sec before the stop time. You have to choose the timeConstant value appropriately to fade out fast enough but not fast enough to cause a click.