我有以下片段,它创建一个振荡器并以一定的音量播放它。我将oscillator
变量保留在函数范围之外,以便在需要时可以使用其他函数停止它。
var oscillator = null;
var isPlaying = false;
function play(freq, gain) {
//stop the oscillator if it's already playing
if (isPlaying) {
o.stop();
isPlaying = false;
}
//re-initialize the oscillator
var context = new AudioContext();
//create the volume node;
var volume = context.createGain();
volume.connect(context.destination);
volume.gain.value = gain;
//connect the oscillator to the nodes
oscillator = context.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.value = freq;
oscillator.connect(volume);
oscillator.connect(context.destination);
//start playing
oscillator.start();
isPlaying = true;
//log
console.log('Playing at frequency ' + freq + ' with volume ' + gain);
}
麻烦的是,增益节点volume
似乎没有像您期望的那样工作。据我了解,增益0
是静音的,增益1
是 100% 音量。但是,在这种情况下,0
作为gain
值传递只会播放静音,而不是完全静音(我希望我能正确解释)。
我究竟做错了什么?有人可以帮忙吗?