/** * Генератор короткой мелодии в WAV. * * Нужен, чтобы музыкальный вопрос работал «из коробки»: в репозитории лежит * файл, а не ссылка на файл, которого нет. Замените его своей записью — * формат и имя значения не имеют, важна строка media.src в паке. * * Запуск: node scripts/make-audio.mjs */ import { writeFileSync, mkdirSync } from 'node:fs' import { fileURLToPath } from 'node:url' const SAMPLE_RATE = 22050 const OUT = fileURLToPath(new URL('../content/media/demo/jingle-bells.wav', import.meta.url)) const NOTES = { C4: 261.63, D4: 293.66, E4: 329.63, F4: 349.23, G4: 392.0, A4: 440.0, B4: 493.88, C5: 523.25, } const BEAT = 0.28 /** «Jingle Bells» — мелодия в общественном достоянии, первые две фразы. */ const MELODY = [ ['E4', 1], ['E4', 1], ['E4', 2], ['E4', 1], ['E4', 1], ['E4', 2], ['E4', 1], ['G4', 1], ['C4', 1], ['D4', 1], ['E4', 4], ['F4', 1], ['F4', 1], ['F4', 1], ['F4', 1], ['F4', 1], ['E4', 1], ['E4', 1], ['E4', 0.5], ['E4', 0.5], ['E4', 1], ['D4', 1], ['D4', 1], ['E4', 1], ['D4', 2], ['G4', 2], ] const samples = [] for (const [note, beats] of MELODY) { const frequency = NOTES[note] const duration = beats * BEAT const total = Math.floor(duration * SAMPLE_RATE) const attack = Math.floor(0.01 * SAMPLE_RATE) const release = Math.floor(0.06 * SAMPLE_RATE) for (let index = 0; index < total; index += 1) { // Простая огибающая: без неё на стыках нот слышны щелчки. let envelope = 1 if (index < attack) envelope = index / attack else if (index > total - release) envelope = Math.max(0, (total - index) / release) const time = index / SAMPLE_RATE const wave = Math.sin(2 * Math.PI * frequency * time) * 0.6 + Math.sin(2 * Math.PI * frequency * 2 * time) * 0.25 + Math.sin(2 * Math.PI * frequency * 3 * time) * 0.1 samples.push(wave * envelope * 0.35) } // Короткая пауза между нотами. const gap = Math.floor(0.01 * SAMPLE_RATE) for (let index = 0; index < gap; index += 1) samples.push(0) } const dataBytes = samples.length * 2 const buffer = Buffer.alloc(44 + dataBytes) buffer.write('RIFF', 0) buffer.writeUInt32LE(36 + dataBytes, 4) buffer.write('WAVE', 8) buffer.write('fmt ', 12) buffer.writeUInt32LE(16, 16) buffer.writeUInt16LE(1, 20) // PCM buffer.writeUInt16LE(1, 22) // моно buffer.writeUInt32LE(SAMPLE_RATE, 24) buffer.writeUInt32LE(SAMPLE_RATE * 2, 28) buffer.writeUInt16LE(2, 32) buffer.writeUInt16LE(16, 34) buffer.write('data', 36) buffer.writeUInt32LE(dataBytes, 40) samples.forEach((sample, index) => { const clamped = Math.max(-1, Math.min(1, sample)) buffer.writeInt16LE(Math.round(clamped * 32767), 44 + index * 2) }) mkdirSync(fileURLToPath(new URL('../content/media/demo/', import.meta.url)), { recursive: true }) writeFileSync(OUT, buffer) const seconds = (samples.length / SAMPLE_RATE).toFixed(1) console.log(`готово: ${OUT} (${seconds} с, ${Math.round(buffer.length / 1024)} КБ)`)