这段代码做了我想要的,它逐渐改变了两个波形的音量。但是,我遇到了很多噼啪声,即每当我以某种方式与浏览器交互时(例如:切换标签时)。任何人都可以解释为什么会这样,如果可以修复,怎么办?
感谢。这里有一个工作演示:https://jsfiddle.net/50cepayr/1/
(顺便说一句 - 据我所知,这与启动和停止音频的“丑陋点击”问题不同(如此处所述:http://alemangui.github.io/blog//2015/12/26/ramp-to-value.html)...噼里啪啦的声音不同与开始/停止无关。)
function getRandArb(min, max) {
return Math.random() * (max - min) + min;
}
var context = new AudioContext();
var frequencyValue = 220;
var oscSaw = context.createOscillator();
oscSaw.type = "sawtooth";
oscSaw.frequency.value = frequencyValue;
oscSaw.start(context.currentTime);
var gainSaw = context.createGain();
gainSaw.gain.value = 0.5*Math.random(); console.log("saw",gainSaw.gain.value);
oscSaw.connect(gainSaw);
var oscTri = context.createOscillator();
oscTri.type = "triangle";
oscTri.frequency.value = frequencyValue;
oscTri.start(context.currentTime);
var gainTri = context.createGain();
gainTri.gain.value = 3*Math.random(); console.log("tri",gainTri.gain.value);
oscTri.connect(gainTri);
var gainOscSum = context.createGain();
gainOscSum.gain.value = 1;
gainSaw.connect(gainOscSum);
gainTri.connect(gainOscSum);
gainOscSum.connect(context.destination);
function changeGainsSmooth(){
var newGainSaw = 0.5*Math.random();
gainSaw.gain.setTargetAtTime(newGainSaw, context.currentTime, 1.9)
console.log("saw",gainSaw.gain.value);
var newGainTri = 3*Math.random();
gainTri.gain.setTargetAtTime(newGainTri, context.currentTime, 1.9)
console.log("tri",gainTri.gain.value);
}
setInterval(changeGainsSmooth,2000);
https://jsfiddle.net/50cepayr/