const fs = require('fs'); const { Midi } = require('@tonejs/midi'); const midiData = fs.readFileSync('song.mid'); const midi = new Midi(midiData); const sampleRate = 44100; let notesByteCode = []; function midiToFrequency(n) { return 440 * Math.pow(2, (n - 69) / 12); } function getADSRCode(startT, endT) { const attack = 50; const release = 50; return `(t<${startT}+${attack}?((t-${startT})/${attack}):t>${endT}-${release}?(${endT}-t)/${release}:1)`; } function getByteCode(note) { const startT = Math.round(note.time * sampleRate); const endT = Math.round((note.time + note.duration) * sampleRate); const freq = midiToFrequency(note.midi); const velocity = note.velocity || 1; const adsr = getADSRCode(startT, endT); return `(t>=${startT}&&t<${endT}?(${velocity}*${adsr}*Math.sin(2*Math.PI*${freq}*t/${sampleRate})*127 + 128):0)`; } midi.tracks.forEach(track => { track.notes.forEach(note => { notesByteCode.push(getByteCode(note)); }); }); const result = `Math.max(${notesByteCode.join(',')})`; fs.writeFileSync('result.txt', result);