midi-file
Install with yarn add midi-file or npm install midi-file.
The parser is loosely based on midi-file-parser and jasmid, but totally rewritten to use arrays instead of strings for portability.
Typescript Usage
import * as fs from 'fs';
import * as midiManager from 'midi-file';
const input = fs.readFileSync('star_wars.mid');
const parsed = midiManager.parseMidi(input);
const output = midiManager.writeMidi(parsed);
const outputBuffer = Buffer.from(output);
fs.writeFileSync('copy_star_wars.mid', outputBuffer);
Raw Javascript Usage
var fs = require('fs')
var parseMidi = require('midi-file').parseMidi
var writeMidi = require('midi-file').writeMidi
var input = fs.readFileSync('star_wars.mid')
var parsed = parseMidi(input)
var output = writeMidi(parsed)
var outputBuffer = Buffer.from(output)
fs.writeFileSync('copy_star_wars.mid', outputBuffer)
The intermediate representation has a 'header' and 'tracks', and each track is an array of events.
Explicit Formatting
Options are provided to writeMidi to control various ambiguities in the MIDI file format.
The following will use byte 0x09 for noteOff messages with velocity zero. (Typically such messages use 0x08).
It will also use running status bytes to compress consecutive events when possible.
var output = writeMidi(parsed, { useByte9ForNoteOff: true, running: true })
When parsing the file with readMidi, each compressed event using running status bytes will have a running flag set on it.
Similarly, each noteOff event that was encoded using 0x09 will have a byte9 property set on it.
By default, writeMidi will defer to each event to indicate the behavior it should use for encoding such ambiguities, which will produce an exact copy of the original file read with parseMidi. However, these options to writeMidi allow the behavior to be overridden at the top-level, which may be relevant if you are generating the MIDI events, rather than just reading them from a file.