/ interactive_tutorials / hardening_softening
Sign in
interactive_tutorials / hardening_softening
hardening_softening / app / js / instrument-chain.js
66 lines · 2.4 KBCodeBlameHistory
7212d95Hardening and softening tutorialJeremy Magland 1// The lab slides' audio chain after the oscillator:
2// u -> dry gain (1 - w) ---------------------\
3// u -> convolver (the instrument's h) -> w ---+-> level stage -> output
4// The instrument is the linear part (instruments.js); the level stage
5// (level-worklet.js) is the non-linear part: loudness normalization and a
6// limiter. Switching instrument crossfades to a new convolver.
8const SWITCH = 0.03; // seconds, for crossfading
9const moduleReady = new WeakMap(); // per audio context
11// Returns { input, output, set({ name, base, scale, wet }), setWet(w), setNormalize(on) }.
12// Connect the oscillator to input and output onward.
13export async function createInstrumentChain(ctx, impulseResponse) {
14 if (!moduleReady.has(ctx)) moduleReady.set(ctx, ctx.audioWorklet.addModule(new URL('./level-worklet.js', import.meta.url)));
15 await moduleReady.get(ctx);
16 const input = ctx.createGain();
17 const dry = ctx.createGain();
18 const level = new AudioWorkletNode(ctx, 'level-processor', { outputChannelCount: [1] });
19 input.connect(dry).connect(level);
20 let wetPath = null; // { convolver, gain }
21 let wet = 0;
22 let hasFilter = false;
24 // the dry path's level: all of u for raw, else 1 - w
25 const setDry = () => dry.gain.setTargetAtTime(hasFilter ? 1 - wet : 1, ctx.currentTime, SWITCH / 3);
27 function set({ name, base, scale, wet: w }) {
28 wet = w;
29 const h = impulseResponse(name, base, ctx.sampleRate, scale);
30 const old = wetPath;
31 if (old) {
32 old.gain.gain.setTargetAtTime(0, ctx.currentTime, SWITCH / 3);
33 setTimeout(() => {
34 old.convolver.disconnect();
35 old.gain.disconnect();
36 }, 5 * SWITCH * 1000);
37 }
38 wetPath = null;
39 hasFilter = Boolean(h);
40 if (h) {
41 const buffer = ctx.createBuffer(1, h.length, ctx.sampleRate);
42 buffer.copyToChannel(h, 0);
43 const convolver = ctx.createConvolver();
44 convolver.normalize = false;
45 convolver.buffer = buffer;
46 const gain = ctx.createGain();
47 gain.gain.value = 0;
48 input.connect(convolver).connect(gain).connect(level);
49 gain.gain.setTargetAtTime(wet, ctx.currentTime, SWITCH / 3);
50 wetPath = { convolver, gain };
51 }
52 setDry();
53 }
55 return {
56 input,
57 output: level,
58 set,
59 setWet: (w) => {
60 wet = w;
61 if (wetPath) wetPath.gain.gain.setTargetAtTime(wet, ctx.currentTime, 0.01);
62 setDry();
63 },
64 setNormalize: (on) => level.port.postMessage({ type: 'normalize', on }),
65 };
↑↓ move↵openescclose