WebAudio 振荡器 "click"
WebAudio oscillator "click"
每当我尝试一个简单的振荡器(检查 this example。它不是我的,但它显示同样的问题)我在开始和结束时听到“咔哒”声。
如何绕过这个问题?
要停止点击,您需要平滑地斜升振荡器而不是立即启动它。类似于以下内容:
var osc = context.createOscillator();
var gain = context.createGain();
osc.connect(gain);
gain.gain.setValueAtTime(0, context.currentTime);
gain.gain.linearRampToValueAtTime(1, context.currentTime + <some small time>);
osc.start();
...
// To stop the oscillator, ramp the gain down.
gain.gain.linearRampToValueAtTime(0, endTime - <small time>);
osc.stop(endTime);
如果不想加增益,可以让振荡在固定周期数后停止:
const ac = new AudioContext
const osc = ac.createOscillator()
const freq = 220
const start = 2 + ac.currentTime
const length = Math.random() * 2
const period = length * freq
const roundedPeriod = Math.round(period)
const correctedLength = roundedPeriod / freq
const end = start + correctedLength
osc.connect(ac.destination)
osc.frequency.value = freq
osc.start(start)
osc.stop(end)
这里有一个更强大的例子:
https://codepen.io/yukulele/pen/QWMZGOZ
每当我尝试一个简单的振荡器(检查 this example。它不是我的,但它显示同样的问题)我在开始和结束时听到“咔哒”声。
如何绕过这个问题?
要停止点击,您需要平滑地斜升振荡器而不是立即启动它。类似于以下内容:
var osc = context.createOscillator();
var gain = context.createGain();
osc.connect(gain);
gain.gain.setValueAtTime(0, context.currentTime);
gain.gain.linearRampToValueAtTime(1, context.currentTime + <some small time>);
osc.start();
...
// To stop the oscillator, ramp the gain down.
gain.gain.linearRampToValueAtTime(0, endTime - <small time>);
osc.stop(endTime);
如果不想加增益,可以让振荡在固定周期数后停止:
const ac = new AudioContext
const osc = ac.createOscillator()
const freq = 220
const start = 2 + ac.currentTime
const length = Math.random() * 2
const period = length * freq
const roundedPeriod = Math.round(period)
const correctedLength = roundedPeriod / freq
const end = start + correctedLength
osc.connect(ac.destination)
osc.frequency.value = freq
osc.start(start)
osc.stop(end)
这里有一个更强大的例子:
https://codepen.io/yukulele/pen/QWMZGOZ