A pure Lua implementation to read midi files using a callback function.
The library allows not only reading all tracks in a midi file at once, but also reading only the header (e.g. to a find out the track count) and then reading a single, specific midi track.
Reading all tracks in a midi file:
local midi = require "midi"
local file = assert(io.open("short-tune.mid"))
midi.process(file, print)
file:close()
Reading only the last track in a midi file:
local midi = require "midi"
local file = assert(io.open("short-tune.mid"))
local tracks = midi.processHeader(file) -- find number of tracks
file:seek("set") -- seek back to the beginning of the file
midi.processTrack(file, print, tracks)
file:close()
The library consists of a single Lua file, namely midi.lua.
The following functions require a stream of a real midi file and use a callback to report individual midi events:
function midi.process(stream, callback, onlyHeader, onlyTrack)
function midi.processHeader(stream, callback)
function midi.processTrack(stream, callback, track)
All functions return the total number of tracks in the midi file.
Parameter | Description | |
---|---|---|
stream |
A stream (e.g. file* ) that points to the start of a midi file. |
required |
callback |
A callback function which is invoked for all midi events. | optional |
onlyHeader |
When set to true , only the header chunk will be processed. |
optional |
onlyTrack |
When set to any integer, only the header chunk and track with this one-based index will be processed. | optional |
track |
Same as onlyTrack but required. |
required |
The following function simply reads a single midi event (excluding the usually preceeding delta-time) from the given stream:
function midi.processEvent(stream, callback, runningStatus)
It returns how many bytes it had to read from the stream, followed by the updated runningStatus.
Parameter | Description | |
---|---|---|
stream |
A stream (e.g. file* ) that points to a midi event. |
required |
callback |
A callback function which is invoked for the midi event. | required |
runningStatus |
The running status of a previous midi event. | optional |
Prints all midi events in the given midi file.
Prints only the midi events of a single track in the midi file.
Handles only specific midi events using a dispatch table.
Lists the signatures, on how the callback is invoked, for each midi event.
Shows how to read single events from a stream.
Calculates the total length of a midi file in seconds.
Also outlines how to convert midi ticks to seconds in general.