JSFiddle - React, Tailwind, and code Playground
HTML
<button id = "button" >
Start then stop oscillators
</button>
JavaScript
var audioContext = new AudioContext();
var fadeIn = 2; //0.1
var fadeOut = 5; //0.3
var gainNode = audioContext.createGain();
var osc = audioContext.createOscillator();
osc.type = "sine";
osc.frequency.value = 300;
osc.connect(gainNode);
gainNode.gain.value = 0;
gainNode.connect(audioContext.destination);
function startAndStop() {
osc.start(audioContext.currentTime);
gainNode.gain.setTargetAtTime(1, audioContext.currentTime, fadeIn);
gainNode.gain.setTargetAtTime(0, audioContext.currentTime + fadeIn, fadeOut);
osc.stop(audioContext.currentTime + fadeIn + fadeOut + 5);
};
var button = document.getElementById("button");
button.addEventListener("click", startAndStop);