我有以下代码片段,它创建一个振荡器并以一定的音量播放它。我将振荡器变量保留在函数范围之外,以便在需要时可以使用其他函数来停止它。
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);
}
问题是,增益节点音量
似乎无法按您的预期工作。据我了解,0
的增益是静音,1
的增益是 100% 音量。但是,在这种情况下,传递 0
作为 gain
值只会播放低沉的声音,而不是完全静音(我希望我能正确解释这一点)。
我做错了什么?有人可以帮忙吗?
最佳答案
问题在于振荡器节点同时连接到增益节点和目标节点。
+---------------+
| |
oscillator ----+----> gain ----+---> destination
所以即使增益节点衰减到0,仍然有另一条路径到达目的地。问题可能出在删除第二个 oscillator.connect
行。
oscillator.connect(volume);
//oscillator.connect(context.destination);
关于javascript 振荡器音量未完全正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35615104/