我知道这听起来很简单或显而易见,但我无法完成这项工作。
请参阅以下代码段:
ctx = new AudioContext();
gain = ctx.createGain();
gain.connect(ctx.destination);
gain.gain.value = 0.5;
osc1 = ctx.createOscillator();
osc1.connect(gain);
osc1.frequency.value = 450;
osc1.start();
osc1.stop(2);
osc2 = ctx.createOscillator();
osc2.connect(gain);
osc2.frequency.value = 500;
osc2.start();
osc2.stop(2);
console.log("playing");
它同时播放两个振荡器,没有问题,但是重复了代码。如果我尝试将冗余代码放入一个函数中,它将无法正常工作。
ctx = new AudioContext();
gain = ctx.createGain();
createAndPlayOsc(450);
createAndPlayOsc(500);
function createAndPlayOsc(freq){
console.log("creating osc with freq " + freq);
var osc = ctx.createOscillator();
osc.connect(gain);
osc.frequency.value = freq;
osc.start();
osc.stop(2);
console.log("playing osc with freq " + freq);
}
即使我发送AudioContext
ctx = new AudioContext();
gain = ctx.createGain();
createAndPlayOsc(450, ctx);
createAndPlayOsc(500, ctx);
function createAndPlayOsc(freq, context){
console.log("creating osc with freq " + freq);
var osc = context.createOscillator();
osc.connect(gain);
osc.frequency.value = freq;
osc.start();
osc.stop(2);
console.log("playing osc with freq " + freq);
}
或gainNode和context
ctx = new AudioContext();
gain = ctx.createGain();
createAndPlayOsc(450, ctx, gain);
createAndPlayOsc(500, ctx, gain);
function createAndPlayOsc(freq, context, gainNode){
console.log("creating osc with freq " + freq);
var osc = context.createOscillator();
osc.connect(gainNode);
osc.frequency.value = freq;
osc.start();
osc.stop(2);
console.log("playing osc with freq " + freq);
}
我缺少什么?
最佳答案
您忘记了将增益连接到上下文:
gain.connect(ctx.destination);