@dawcore/midi
v0.0.6
Published
Framework-agnostic MIDI file parsing, and loading a MIDI file as waveform-playlist tracks
Maintainers
Readme
@dawcore/midi
Framework-agnostic MIDI file parsing, and loading a .mid file as waveform-playlist tracks. No React, no DOM, no Lit — plain functions built on @tonejs/midi.
Used by @dawcore/components (the Lit web component layer, via editor.loadMidi()) and by React apps on @waveform-playlist/browser (loadMidiTracks, whose tracks go into the arrangement). It replaces @waveform-playlist/midi, which is no longer published: the names are the same, only the import changes.
Installation
npm install @dawcore/midiNo peer dependencies; @tonejs/midi and @waveform-playlist/core are regular dependencies. @dawcore/components declares this package as an optional peer dependency — add it to your own dependencies to enable editor.loadMidi() (it's dynamic-imported on first call, so non-MIDI users ship zero parser bytes).
Quick Start
import { parseMidiUrl, parseMidiFile } from '@dawcore/midi';
// Fetch and parse a .mid URL (optional AbortSignal for cancellation)
const midi = await parseMidiUrl('/media/song.mid');
// midi: { tracks, duration, name, bpm, timeSignature }
for (const track of midi.tracks) {
// track: { name, notes, duration, channel, instrument, programNumber }
console.log(track.name, track.notes.length + ' notes');
}
// Or parse an ArrayBuffer you already have (e.g. from a File input)
const buffer = await file.arrayBuffer();
const parsed = parseMidiFile(buffer, { flatten: true }); // merge all tracks into oneNote timings are in seconds, already tempo-adjusted by @tonejs/midi. Tracks without notes are filtered out.
Loading tracks for an arrangement
loadMidiTracks(src, options) loads a URL, a File or a Blob as ClipTrack[] with kind: 'midi', one track per MIDI track of the file (one in all with flatten). It is a function, not a hook: the app keeps its own loading and error state and adds the tracks to the arrangement that WebAudioProvider plays. Every call makes new track and clip ids.
import { useEffect, useState } from 'react';
import { loadMidiTracks } from '@dawcore/midi';
import { WebAudioProvider, useCreateArrangement } from '@waveform-playlist/browser';
function MidiPlaylist() {
// Starts empty; the MIDI tracks are added once the file has loaded
const arrangement = useCreateArrangement();
const [loaded, setLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const controller = new AbortController();
loadMidiTracks('/music/song.mid', { signal: controller.signal })
.then((tracks) => {
if (arrangement.getTracks().length === 0) {
// What the app adds is not an undo step
tracks.forEach((track) => arrangement.addTrack(track));
}
setLoaded(true);
})
.catch((err: unknown) => {
// An abort (unmount, StrictMode's first run) is not an error
if (!controller.signal.aborted) setError(err instanceof Error ? err.message : String(err));
});
return () => controller.abort();
}, [arrangement]);
if (error) return <p>Error: {error}</p>;
if (!loaded) return <p>Loading MIDI…</p>;
// Rendered once the tracks are in: the playlist's ready happens once per mount
return (
<WebAudioProvider arrangement={arrangement}>
{/* your UI */}
</WebAudioProvider>
);
}The clips' times are seconds, so no sample rate is passed and the tracks play on any hardware. Playing the notes (piano roll, SoundFont or PolySynth) is @waveform-playlist/browser with @waveform-playlist/playout; see the MIDI guide.
API
parseMidiFile(data: ArrayBuffer, options?)— parse MIDI data intoParsedMidiparseMidiUrl(url: string, options?, signal?)— fetch and parse a.midURL- Options:
{ flatten?: boolean }— merge all MIDI tracks into a single track loadMidiTracks(src: string | File | Blob, options?: LoadMidiTracksOptions)— a file askind: 'midi'tracks:
interface LoadMidiTracksOptions {
flatten?: boolean; // merge all tracks in the file into one ClipTrack (default false)
start?: number; // clip position on timeline, in seconds, 0 or more (default 0)
duration?: number; // clip duration in seconds, above 0 (default: end of the track's last note)
// a number that is not finite rejects with a TypeError, one out of range with a RangeError,
// before anything is fetched or read; a null start or duration was not given
name?: string; // names the track and its clip when the file yields exactly one track
signal?: AbortSignal; // an aborted signal rejects with the signal's reason
}- Types:
ParsedMidi,ParsedMidiTrack,ParseMidiOptions,LoadMidiTracksOptions,MidiLoadOptions,MidiLoadResult. The last two areeditor.loadMidi()'s (@dawcore/components):MidiLoadOptionsis{ startTime?, signal?, undoable? }(undoable: falseadds the tracks with no undo step, for content the page loads itself; left out, the call is one undo step), andMidiLoadResult.trackIdsholds the ids of the tracks added (no<daw-track>element is created)
A URL that does not answer with an OK status rejects with Failed to fetch MIDI file <url>: <status>, with the status text after the code when there is one (Failed to fetch MIDI file /missing.mid: 404 Not Found); data that is not a MIDI file rejects with parseMidiFile: invalid or corrupt MIDI data (<n> bytes): ….
Coming from @waveform-playlist/midi: change the import. Its useMidiTracks hook (13.x) was removed; the upgrade guide has the replacement for each of its options.
Examples & Documentation
examples/dawcore-tone/midi-load.html— loading a.midfile (URL or file input) into<daw-editor>viaeditor.loadMidi(), with cancellation (pnpm example:dawcore-tone)- MIDI guide — covers both the React (
loadMidiTracks) and Web Components (editor.loadMidi()) paths, which both use this package - MIDI example
License
MIT
