Add pink, white and brown oscillators

This commit is contained in:
Raphael Forment 2023-09-30 14:07:33 +02:00
parent 8a741952df
commit c2481e460b

View file

@ -20,8 +20,11 @@ const fm = (osc, harmonicityRatio, modulationIndex, wave = 'sine') => {
return mod(modfreq, modgain, wave); return mod(modfreq, modgain, wave);
}; };
export function registerSynthSounds() { export function registerSynthSounds() {
['sine', 'square', 'triangle', 'sawtooth'].forEach((wave) => { ['sine', 'square', 'triangle',
'sawtooth', 'pink', 'white',
'brown'].forEach((wave) => {
registerSound( registerSound(
wave, wave,
(t, value, onended) => { (t, value, onended) => {
@ -63,7 +66,6 @@ export function registerSynthSounds() {
vibmod, vibmod,
partials: n, partials: n,
}); });
// FM + FM envelope // FM + FM envelope
let stopFm, fmEnvelope; let stopFm, fmEnvelope;
if (fmModulationIndex) { if (fmModulationIndex) {
@ -146,9 +148,57 @@ export function waveformN(partials, type) {
return osc; return osc;
} }
export function getNoiseOscillator({ t, ac, type = 'white' }) {
const bufferSize = 2 * ac.sampleRate;
const noiseBuffer = ac.createBuffer(1, bufferSize, ac.sampleRate);
const output = noiseBuffer.getChannelData(0);
let lastOut = 0;
let b0, b1, b2, b3, b4, b5, b6;
b0 = b1 = b2 = b3 = b4 = b5 = b6 = 0.0;
for (let i = 0; i < bufferSize; i++) {
if (type === 'white') {
output[i] = Math.random() * 2 - 1;
} else if (type === 'brown') {
let white = Math.random() * 2 - 1;
output[i] = (lastOut + (0.02 * white)) / 1.02;
lastOut = output[i];
} else if (type === 'pink') {
let white = Math.random() * 2 - 1;
b0 = 0.99886 * b0 + white * 0.0555179;
b1 = 0.99332 * b1 + white * 0.0750759;
b2 = 0.96900 * b2 + white * 0.1538520;
b3 = 0.86650 * b3 + white * 0.3104856;
b4 = 0.55000 * b4 + white * 0.5329522;
b5 = -0.7616 * b5 - white * 0.0168980;
output[i] = b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362;
output[i] *= 0.11;
b6 = white * 0.115926;
}
}
const o = ac.createBufferSource();
o.buffer = noiseBuffer;
o.loop = true;
o.start(t);
return {
node: o,
stop: (time) => o.stop(time)
};
}
export function getOscillator({ s, freq, t, vib, vibmod, partials }) { export function getOscillator({ s, freq, t, vib, vibmod, partials }) {
// Make oscillator with partial count // Make oscillator with partial count
let o; let o;
if (['pink', 'white', 'brown'].includes(s)) {
let noiseOscillator = getNoiseOscillator({ t: t, ac: getAudioContext(), type: s })
return {
node: noiseOscillator.node,
stop: noiseOscillator.stop
}
} else {
if (!partials || s === 'sine') { if (!partials || s === 'sine') {
o = getAudioContext().createOscillator(); o = getAudioContext().createOscillator();
o.type = s || 'triangle'; o.type = s || 'triangle';
@ -178,4 +228,6 @@ export function getOscillator({ s, freq, t, vib, vibmod, partials }) {
o.stop(time); o.stop(time);
}, },
}; };
}
} }