function buildMidi(notes) { const division = 480; const ticksPerSecond = 960; const events = []; notes.forEach((note) => { const startTick = Math.max(0, Math.round(note.start * ticksPerSecond)); const endTick = Math.max(startTick + 24, Math.round((note.start + note.duration) * ticksPerSecond)); events.push({ tick: startTick, order: 1, data: [0x90, note.pitch, note.velocity] }); events.push({ tick: endTick, order: 0, data: [0x80, note.pitch, 0] }); }); events.sort((a, b) => a.tick - b.tick || a.order - b.order); const track = [0x00, 0xff, 0x51, 0x03, 0x07, 0xa1, 0x20]; let previousTick = 0; events.forEach((event) => { track.push(...variableLength(event.tick - previousTick), ...event.data); previousTick = event.tick; }); track.push(0x00, 0xff, 0x2f, 0x00); return new Uint8Array([ 0x4d, 0x54, 0x68, 0x64, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x01, (division >> 8) & 0xff, division & 0xff, 0x4d, 0x54, 0x72, 0x6b, (track.length >>> 24) & 0xff, (track.length >>> 16) & 0xff, (track.length >>> 8) & 0xff, track.length & 0xff, ...track ]); }