WebAudio 没有提供任何音频输出

WebAudio isn't giving any audio output

HTML

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

脚本

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;
}

没有音频输出,但频率值确实发生了变化,“fr”也得到了更新。

不允许AudioContext自动启动。

必须在页面 user gesture 之后恢复(或创建)

试试下面的示例代码,你可以做相应的修改。

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>