JSFiddle - React, Tailwind, and code Playground
HTML
<input type="button" value="wooo!" id="start1">
<input type="button" value="shhh..." id="stop1">
JavaScript
var context = new AudioContext();
var startButton1 = document.getElementById("start1");
var stopButton1 = document.getElementById("stop1");
Inst = function (){
var inst = {}
inst.makeOsc = function() {
inst.osc = context.createOscillator();
inst.gain = context.createGain();
inst.osc.connect(inst.gain);
inst.gain.connect(context.destination)
inst.gain.gain.value = 0;
}
inst.playTone = function () {
inst.makeOsc();
inst.osc.start();
inst.gain.gain.setTargetAtTime(1, context.currentTime, 0.1);
}
inst.stopTone = function () {
inst.gain.gain.setTargetAtTime(0, context.currentTime, 0.1);
inst.osc.stop(context.currentTime+0.5); // check out how you'll still hear a bit of a pop even up to 0.4
}
return inst;
}
var instrument = Inst();
startButton1.addEventListener('click', function() {
instrument.playTone();
});
stopButton1.addEventListener('click', function() {
instrument.stopTone();
// hmmm, timing...
});