我知道这听起来很简单或明显,但我无法做到这一点。
请参阅此代码段:
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);
}
我缺少什么?
答案 0 :(得分:1)
您忘了将收益连接到上下文:
gain.connect(ctx.destination);