Click web sound, even when using exponentialRampToValueAtTime

I try to avoid the ugly click sound when the oscillator stops, so I decided to try some attenuation with exponentialRampToValueAtTime. Like this:

var playButton = document.getElementById('play');
var stopButton = document.getElementById('stop');

var context = new AudioContext();
var gainNode = context.createGain();
var oscillator =  context.createOscillator();

gainNode.connect(context.destination);
oscillator.connect(gainNode);
gainNode.gain.setValueAtTime(1, context.currentTime);
oscillator.start();
gainNode.gain.exponentialRampToValueAtTime(0.0001, context.currentTime + 1);
Run code

This works well, there is no click sound, and the ramp down is smooth. However, as soon as I do this using buttons and event listeners, an ugly click returns, and somehow the ramp down is coarser

btw, wait 1 second after pressing “Stop” and before pressing “play” again or ugly things :)

var playButton = document.getElementById('play');
var stopButton = document.getElementById('stop');

var context = new AudioContext();
var gainNode = context.createGain();
var oscillator;

gainNode.connect(context.destination);


playButton.addEventListener('click', function() {
  oscillator = context.createOscillator();
  oscillator.connect(gainNode);
  gainNode.gain.setValueAtTime(1, context.currentTime);
  oscillator.start();
}, false);

stopButton.addEventListener('click', function() {
  gainNode.gain.exponentialRampToValueAtTime(0.0001, context.currentTime + 1);
  setTimeout(function(){
  	oscillator.stop();
  }, 1000)
}, false);
<button id="play">play</button>
<button id="stop">stop</button>
Run code

I clearly lack theory. The code is very similar, with the exception of listeners, and the result of both fragments is very different in quality. Could you explain where this difference comes from?

/?

!

+4
1

, , . , !

var playButton = document.getElementById('play');
var stopButton = document.getElementById('stop');

var context = new AudioContext();
var gainNode = context.createGain();
var oscillator;

gainNode.connect(context.destination);


playButton.addEventListener('click', function() {
  oscillator = context.createOscillator();
  oscillator.connect(gainNode);
  gainNode.gain.setValueAtTime(1, context.currentTime);
  oscillator.start();
}, false);

stopButton.addEventListener('click', function() {
  gainNode.gain.setValueAtTime(gainNode.gain.value, context.currentTime);
  gainNode.gain.exponentialRampToValueAtTime(0.0001, context.currentTime + 1);
  setTimeout(function(){
  	oscillator.stop();
  }, 1000)
}, false);
<button id="play">play</button>
<button id="stop">stop</button>
+6

Source: https://habr.com/ru/post/1621823/


All Articles