我正在使用网络音频 api 构建一个带有一些效果的 fm 合成器。一切正常,但是音频非常有问题,并开始冻结和剪切,我认为这是我的浏览器无法一次处理所有音频信息的结果。
每次播放音符时都会将很多音频节点添加到音频上下文中,所以我想知道未使用的节点是否会减慢音频上下文的速度,如果是的话,有什么办法可以破坏它们?
我的代码:
play = function(s, p) {
//setup
var now = AudioContext.currentTime;
var osc1 = AudioContext.createOscillator(),
osc2 = AudioContext.createOscillator(),
osc3 = AudioContext.createOscillator(),
osc4 = AudioContext.createOscillator(),
gain1 = AudioContext.createGain(),
gain2 = AudioContext.createGain(),
gain3 = AudioContext.createGain(),
gain4 = AudioContext.createGain(),
filter = new tuna.Filter(),
phaser = new tuna.Chorus();
convolver = new tuna.Convolver();
var pitch = p
osc1.type = 'sine';
osc2.type = 'square';
osc3.type = 'triangle';
osc4.type = 'sine';
osc1.frequency.value = pitch * 1.5
osc2.frequency.value = pitch * 8
osc3.frequency.value = pitch
osc4.frequency.value = pitch/2
gain1.gain.setValueAtTime(0,now)
gain2.gain.setValueAtTime(0,now)
gain3.gain.setValueAtTime(0,now)
gain4.gain.setValueAtTime(0,now)
gain1.gain.linearRampToValueAtTime(s[1].value * 1500,now + s[4].value)
gain2.gain.linearRampToValueAtTime(s[0].value * 1500,now + s[4].value)
gain3.gain.linearRampToValueAtTime(1,now + s[4].value)
gain4.gain.linearRampToValueAtTime(s[1].value/2,now + s[4].value)
gain1.gain.linearRampToValueAtTime(0,now + s[4].value + s[5].value)
gain2.gain.linearRampToValueAtTime(0,now + s[4].value + s[5].value)
gain3.gain.linearRampToValueAtTime(0,now + s[4].value + s[5].value)
gain4.gain.linearRampToValueAtTime(0,now + s[4].value + s[5].value)
filter.frequency = s[2].value * 2200
filter.Q = s[0].value * 10
convolver.wetLevel = s[3].value/10
phaser.rate = s[3].value/10
osc3.frequency.value = pitch * 0.666
osc1.connect(gain1);
osc2.connect(gain2);
osc3.connect(gain3);
osc4.connect(gain4);
gain1.connect(osc2.frequency);
gain2.connect(osc3.frequency);
gain3.connect(filter.input);
gain4.connect(filter.input)
filter.output.connect(convolver.input);
convolver.output.connect(phaser.input);
phaser.output.connect(AudioContext.destination);
osc1.start();
osc2.start();
osc3.start();
osc4.start();
setTimeout(function(){
osc1.stop();
osc2.stop();
osc3.stop();
osc4.stop();
}, (s[4].value+s[5].value)*1000)
}
play([0.4, 0.4, 0.4, 0.4, 0.4],440);
它看起来很丑,但我想不出另一种播放声音的方法。
我正在使用 tuna js 来创建合唱、混响和过滤器。
另外,如果有任何关于如何低级优化 javascript 的信息,我将不胜感激。