WebAudio isn't giving any audio output

82 Views Asked by At

HTML

<input type="range" onchange="play()" max=880 />
    <h2 id="fr">000hz</h2>
    <button type="button" onclick="stop()">STOP</button>

SCRIPT

var ctx = new AudioContext();
var osc = ctx.createOscillator();
var gain = ctx.createGain();
osc.connect(gain);
gain.connect(ctx.destination);
gain.gain.value=0;
osc.start(0);
var f = document.querySelector("input");
f.addEventListener("input",(event)=>{
osc.frequency.value=event.target.value;
document.querySelector("h2").innerHTML = f.value + "hz"});
function play(){
  gain.gain.value = 1;
}
function stop(){
  gain.gain.value = 0;
}

There is no audio output but the frequency values do get logged on change and "fr" also gets updated.

1

There are 1 best solutions below

0
On BEST ANSWER

The AudioContext is not allowed to start automatically.

It must be resumed (or created) after a user gesture on the page

Try below sample code, you can do a modification accordingly.

var ctx = new AudioContext();

var osc = ctx.createOscillator();
var gain = ctx.createGain();


function start() {

  osc.connect(gain);
  gain.connect(ctx.destination);
  gain.gain.value = 10;
  osc.start(0);

}


var f = document.querySelector("input");
f.addEventListener("input", (event) => {
  osc.frequency.value = event.target.value;
  document.querySelector("h2").innerHTML = f.value + "hz"
});

function play() {
  gain.gain.value = 1;
}

function stop() {
  gain.gain.value = 0;
}
<input type="range" onchange="play()" max=880 />

<h2 id="fr"></h2>
<button type="button" onclick="start()">START</button>
<button type="button" onclick="stop()">STOP</button>