// Mixage voix off + musique, avec baisse automatique de la musique sous la voix process.chdir(__dirname); const fs = require('fs'); const SR = 48000; const wav = fs.readFileSync('music.wav'); const N = (wav.length - 44) / 4; const L = new Float32Array(N), R = new Float32Array(N), V = new Float32Array(N); for (let k = 0; k < N; k++) { L[k] = wav.readInt16LE(44 + k * 4) / 32768; R[k] = wav.readInt16LE(46 + k * 4) / 32768; } // voix : chaque réplique normalisée puis posée à son instant for (const { t, wav: f } of JSON.parse(fs.readFileSync('vo/plan.json'))) { const b = fs.readFileSync(f), n = (b.length - 44) / 2; let pk = 0; const s = new Float32Array(n); for (let i = 0; i < n; i++) { s[i] = b.readInt16LE(44 + i * 2) / 32768; pk = Math.max(pk, Math.abs(s[i])); } const g = .9 / pk, s0 = Math.round(t * SR); for (let i = 0; i < n; i++) if (s0 + i < N) V[s0 + i] += s[i] * g; } // compression légère de la voix (plus présente sur un téléphone) { let env = 0; for (let k = 0; k < N; k++) { const a = Math.abs(V[k]); env = a > env ? env + (a - env) * .01 : env + (a - env) * .0003; const over = Math.max(0, env - .35); V[k] *= (env > .35 ? (.35 + over * .4) / env : 1) * 1.5; } } // enveloppe de présence de la voix → baisse de la musique à -10 dB (attaque 40 ms, relâche 300 ms) const duck = new Float32Array(N); { let e = 0; const att = 1 - Math.exp(-1 / (.04 * SR)), rel = 1 - Math.exp(-1 / (.3 * SR)); // anticipation de 60 ms pour que la musique baisse juste avant le premier mot const look = Math.round(.06 * SR); for (let k = 0; k < N; k++) { const a = Math.abs(V[Math.min(N - 1, k + look)]) > .02 ? 1 : 0; e += (a - e) * (a > e ? att : rel); duck[k] = 1 - .68 * e; } } let pk = 0; for (let k = 0; k < N; k++) { L[k] = Math.tanh(L[k] * duck[k] * .9 + V[k]); R[k] = Math.tanh(R[k] * duck[k] * .9 + V[k]); pk = Math.max(pk, Math.abs(L[k]), Math.abs(R[k])); } const g = .89 / pk, out = Buffer.alloc(44 + N * 4); out.write('RIFF', 0); out.writeUInt32LE(36 + N * 4, 4); out.write('WAVE', 8); out.write('fmt ', 12); out.writeUInt32LE(16, 16); out.writeUInt16LE(1, 20); out.writeUInt16LE(2, 22); out.writeUInt32LE(SR, 24); out.writeUInt32LE(SR * 4, 28); out.writeUInt16LE(4, 32); out.writeUInt16LE(16, 34); out.write('data', 36); out.writeUInt32LE(N * 4, 40); for (let k = 0; k < N; k++) { out.writeInt16LE(Math.round(L[k] * g * 32767), 44 + k * 4); out.writeInt16LE(Math.round(R[k] * g * 32767), 46 + k * 4); } fs.writeFileSync('mix.wav', out); console.log('mix.wav ok');