以下代码遵循MDN 文档,但导致突然静音而不是 2 秒长的淡出:
const audioContext = new window.AudioContext();
let oscillator;
let gainNode;
document.getElementById("playSweep").addEventListener("click", () => {
oscillator = audioContext.createOscillator();
oscillator.type = "sine"; // Sine wave
oscillator.frequency = 200;
gainNode = audioContext.createGain();
gainNode.gain.setValueAtTime(1, audioContext.currentTime);
oscillator.connect(gainNode);
gainNode.connect(audioContext.destination);
oscillator.start();
});
document.getElementById("fadeOut").addEventListener("click", () => {
gainNode.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + 2);
});
document.getElementById("fadeOut2").addEventListener("click", () => {
gainNode.gain.linearRampToValueAtTime(0.001, audioContext.currentTime + 2);
});
<button id="playSweep">Play Frequency Sweep</button>
<button id="fadeOut">Exp Fade Out</button>
<button id="fadeOut2">Lin Fade Out</button>
即使是线性版本,我们也可以听到咔嗒声,这不是干净的淡出。
如何在 JS Web Audio API 中正确淡出?