Skip to content

Convert Audio to MIDI in JavaScript ​

To convert a recording to MIDI in JavaScript, decode it with Audio.fromMemory, pass the samples to transcribe(), put the returned events in a Project MIDI clip, and write project.exportSmf() to a .mid file. transcribe() finds the notes and exportSmf() is what turns them into a file. The script below does all of it in Node with the WebAssembly package.

js
import { readFileSync, writeFileSync } from 'node:fs';
import { Audio, Project, init, transcribe } from '@libraz/libsonare';

await init();

const audio = Audio.fromMemory(readFileSync('take.wav'));
const project = new Project();
try {
  const { events, noteCount, tempoBpm } = transcribe({
    samples: audio.data,
    sampleRate: audio.sampleRate,
  });

  // The events sit on a constant-tempo grid at tempoBpm; give the project the same tempo.
  project.setTempoSegments([{ startPpq: 0, bpm: tempoBpm }]);
  const { clipId } = project.addMidiClip(0, Math.ceil((audio.durationSec * tempoBpm) / 60));
  project.setMidiEvents(clipId, events);

  writeFileSync('take.mid', project.exportSmf());
  console.log(`${noteCount} notes at ${tempoBpm.toFixed(1)} BPM -> take.mid`);
} finally {
  project.destroy();
  audio.destroy();
}

In a browser the only change is where the bytes come from and where they go: decode with await Audio.fromMemoryWithBrowserFallback(bytes) and offer new Blob([project.exportSmf()], { type: 'audio/midi' }) as a download. The Piano Transcription demo runs this path on a recording you open.

What you need

  • Install: npm install @libraz/libsonare (Node.js 22.12 or later).
  • An audio file: a WAV or MP3 of one melodic line, such as a voice or a lead. For chords and piano, pass polyphonic: true; for a full band mix, separate the instrument first.

Reading the result ​

  • events are note-on and note-off pairs in the shape project.setMidiEvents() takes. Each carries ppq (the position in quarter notes from the start, not seconds) and the packed MIDI 2.0 words word0 and word1. A note is two events, so events.length is always 2 * noteCount.
  • noteCount is the number of notes. Finding none is not an error: silence comes back as an empty events array and noteCount of 0.
  • tempoBpm is the tempo the ppq positions were built on. Leave tempoBpm out of the request and it is detected, falling back to 120 when nothing usable is found; pass one to force it.
  • tuningCents is the offset from A440 the pitches were measured against. For a recording that is not at A440, pass referenceHz: 'auto'.
  • Mono only. Audio holds one channel, so a stereo file is folded to mono on load.

The library does not separate instruments, and a recording with several pitched parts yields notes for all of them.