Library to convert a JSON representation of a MIDI file to an encoded binary MIDI file.
This package works with Node.js, Deno, BrowsersIt is unknown whether this package works with Cloudflare Workers, Bun
JSR Score
100%
Published
3 months ago (1.1.1)
import type { MidiFile } from 'jsr:@midi-json-tools/midi-to-json@^1.1.1'; import { encodeHeaderChunk } from './utils/encode-header-chunk.ts'; import { encodeTrackChunk } from './utils/encode-track-chunk.ts'; import { joinArrayBuffers } from './utils/join-array-buffers.ts'; /** * This function takes in a JSON representation of a MIDI file and encodes it to binary */ export function jsonToMidi({ division, format, tracks, }: MidiFile): ArrayBufferLike { const arrayBuffers = []; try { arrayBuffers.push(encodeHeaderChunk(division, format, tracks)); } catch (err) { throw new Error('The given JSON object seems to be invalid.'); } for (const track of tracks) { try { arrayBuffers.push(encodeTrackChunk(track)); } catch (err) { if ( (err as Error).message.match( /Unencodable\sevent\sat\sposition\s[0-9]+\./, ) ) { const index = tracks.indexOf(track); throw new Error( `${(err as Error).message.slice(0, -1)} of the track at index ${index}.`, ); } throw err; } } return joinArrayBuffers(arrayBuffers); }