javascript – Why does this Web Audio tone composition sound different after few initial plays?
I’m trying to mimic piano sounds by composing 3 harmonics of a given frequency with oscillator and gain nodes of the Web Audio API.
const button = document.getElementById('playButton');
const context = new AudioContext();
button.addEventListener('click', () => play(440));
function play(freq) {
playHarmonic(freq);
playHarmonic(freq * 3 / 2, 1 / 1.2, 1 / 1.3);
playHarmonic(freq * 2, 1 / 1.5, 1 / 1.5);
}
function playHarmonic(freq, ampScaler = 1, scaler = 1) {
const osc = context.createOscillator();
const gain = context.createGain();
const ct = context.currentTime;
osc.frequency.value = freq;
osc.connect(gain);
gain.connect(context.destination);
gain.gain.value = 0;
gain.gain.linearRampToValueAtTime(0, ct + 0.005);
gain.gain.linearRampToValueAtTime(1 * ampScaler / 3, (ct + 0.07) * scaler);
gain.gain.linearRampToValueAtTime(0.6 * ampScaler / 3, (ct + 0.19) * scaler);
gain.gain.linearRampToValueAtTime(0.75 * ampScaler / 3, (ct + 0.26) * scaler);
gain.gain.linearRampToValueAtTime(0.6 * ampScaler / 3, (ct + 0.37) * scaler);
gain.gain.linearRampToValueAtTime(0.2 * ampScaler / 3, (ct + 0.67) * scaler);
gain.gain.linearRampToValueAtTime(0, (ct + 2.7) * scaler);
osc.start();
osc.stop((ct + 2.7) * scaler);
}
But after a couple of initial plays, the sound turns different. Why does that happen?
Can you also suggest a better setting to create piano-like sounds?
Read more here: Source link