0

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”也会更新。

4

1 回答 1

0

AudioContext不允许自动启动。

它必须在页面上的用户手势后恢复(或创建)

试试下面的示例代码,您可以进行相应的修改。

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>

于 2021-02-24T13:16:28.867 回答