// The lab slides' audio chain after the oscillator: // u -> dry gain (1 - w) ---------------------\ // u -> convolver (the instrument's h) -> w ---+-> level stage -> output // The instrument is the linear part (instruments.js); the level stage // (level-worklet.js) is the non-linear part: loudness normalization and a // limiter. Switching instrument crossfades to a new convolver. const SWITCH = 0.03; // seconds, for crossfading const moduleReady = new WeakMap(); // per audio context // Returns { input, output, set({ name, base, scale, wet }), setWet(w), setNormalize(on) }. // Connect the oscillator to input and output onward. export async function createInstrumentChain(ctx, impulseResponse) { if (!moduleReady.has(ctx)) moduleReady.set(ctx, ctx.audioWorklet.addModule(new URL('./level-worklet.js', import.meta.url))); await moduleReady.get(ctx); const input = ctx.createGain(); const dry = ctx.createGain(); const level = new AudioWorkletNode(ctx, 'level-processor', { outputChannelCount: [1] }); input.connect(dry).connect(level); let wetPath = null; // { convolver, gain } let wet = 0; let hasFilter = false; // the dry path's level: all of u for raw, else 1 - w const setDry = () => dry.gain.setTargetAtTime(hasFilter ? 1 - wet : 1, ctx.currentTime, SWITCH / 3); function set({ name, base, scale, wet: w }) { wet = w; const h = impulseResponse(name, base, ctx.sampleRate, scale); const old = wetPath; if (old) { old.gain.gain.setTargetAtTime(0, ctx.currentTime, SWITCH / 3); setTimeout(() => { old.convolver.disconnect(); old.gain.disconnect(); }, 5 * SWITCH * 1000); } wetPath = null; hasFilter = Boolean(h); if (h) { const buffer = ctx.createBuffer(1, h.length, ctx.sampleRate); buffer.copyToChannel(h, 0); const convolver = ctx.createConvolver(); convolver.normalize = false; convolver.buffer = buffer; const gain = ctx.createGain(); gain.gain.value = 0; input.connect(convolver).connect(gain).connect(level); gain.gain.setTargetAtTime(wet, ctx.currentTime, SWITCH / 3); wetPath = { convolver, gain }; } setDry(); } return { input, output: level, set, setWet: (w) => { wet = w; if (wetPath) wetPath.gain.gain.setTargetAtTime(wet, ctx.currentTime, 0.01); setDry(); }, setNormalize: (on) => level.port.postMessage({ type: 'normalize', on }), }; }