-------------------------------------------------------------------------------- --! @title MidiFilePlayer --! @brief Load a MIDI File and Play It Back in Musical Time --! @category MidiTools --! --! Lets the user pick a Standard MIDI File, loads it with loadMidi and plays all --! of its tracks at the host tempo, optionally looped and transposed. The events --! of every track are merged in time order and each one is posted with --! postMidiEvent once it is due: the timestamps are in ticks, converted to beats --! with the sequence's division and waited for with waitBeat. --! --! postMidiEvent sends events without voice ids, so the script keeps its own list --! of sounding notes to release them when playback stops or loops, and to send --! each note-off with the transposition its note-on was played with. --! --! @demonstrates loadMidi, MidiSequence, MidiEvent, postMidiEvent, browseForFile, waitBeat -------------------------------------------------------------------------------- local loadButton = Button{"Load MIDI", bounds = {10, 10, 100, 30}} -- Not persistent: a preset load must never start playback on its own. local play = OnOffButton{"Play", false, bounds = {120, 10, 80, 30}, persistent = false} local loop = OnOffButton{"Loop", true, bounds = {210, 10, 80, 30}} local transpose = Knob{"Transpose", 0, -24, 24, true, bounds = {300, 5, 90, 40}} local status = Label{"status", bounds = {10, 50, 380, 20}, text = "No file loaded"} local sequence = nil local generation = 0 -- bumped to cancel the playback thread local sounding = {} -- [channel * 128 + file note] = note actually played -- Only channel events are forwarded; anything else a file may hold is skipped. local CHANNEL_EVENTS = { [Event.ControlChange] = true, [Event.ProgramChange] = true, [Event.PitchBend] = true, [Event.AfterTouch] = true, [Event.PolyAfterTouch] = true, } local function releaseAll() for key, played in pairs(sounding) do postMidiEvent(uvi.MidiEvent(0, math.floor(key / 128), Event.NoteOff, played, 0)) end sounding = {} end -- Posts a copy: getEvent returns the event stored in the sequence, so editing -- it would transpose the file itself, once more on every loop. local function send(ev) local key = ev.channel * 128 + ev.byte1 if ev.type == Event.NoteOn and ev.byte2 > 0 then local played = math.max(0, math.min(127, ev.byte1 + transpose.value)) sounding[key] = played postMidiEvent(uvi.MidiEvent(0, ev.channel, Event.NoteOn, played, ev.byte2)) elseif ev.type == Event.NoteOn or ev.type == Event.NoteOff then -- velocity 0 is a note-off local played = sounding[key] if played then sounding[key] = nil postMidiEvent(uvi.MidiEvent(0, ev.channel, Event.NoteOff, played, 0)) end elseif CHANNEL_EVENTS[ev.type] then postMidiEvent(uvi.MidiEvent(0, ev.channel, ev.type, ev.byte1, ev.byte2)) end end -- Plays the sequence once; returns the tick it stopped at, nil when cancelled. local function playOnce(seq, myGeneration) local cursor = {} for t = 1, seq.numTracks do cursor[t] = 1 end local tick = 0 while true do -- Earliest pending event across all tracks (tracks are sorted by time). local track, due = nil, math.huge for t = 1, seq.numTracks do if cursor[t] <= seq:getNumEventsForTrack(t) then local ts = seq:getEvent(t, cursor[t]).timestamp if ts < due then track, due = t, ts end end end if not track then return tick end -- Waiting the tick difference follows the tempo, and skipping zero -- deltas keeps simultaneous events on the same sample. if due > tick then waitBeat((due - tick) / seq.division) tick = due end if myGeneration ~= generation then return nil end send(seq:getEvent(track, cursor[track])) cursor[track] = cursor[track] + 1 end end local function playback(seq, myGeneration) repeat local endTick = playOnce(seq, myGeneration) if not endTick then return end -- Loop on whole bars so the file keeps its phase against the host. local num, den = getTimeSignature() local barTicks = seq.division * num * 4 / den local loopTick = math.max(1, math.ceil(endTick / barTicks)) * barTicks waitBeat((loopTick - endTick) / seq.division + 1e-6) -- Cancelled during the wait: a new playback may already be sounding. if myGeneration ~= generation then return end releaseAll() -- notes held across the loop point would otherwise pile up until not loop.value play:setValue(false, false) -- finished on its own: reflect it on the button end play.changed = function(self) generation = generation + 1 -- the previous playback thread exits at its next wake-up local myGeneration = generation local seq = self.value and sequence or nil if self.value and not seq then self:setValue(false, false) -- nothing to play yet end -- A widget callback cannot wait, so the work goes to a thread. Flushing the -- old notes first, in the same thread, keeps them from cutting the new ones. spawn(function() releaseAll() if seq then playback(seq, myGeneration) end end) end loadButton.changed = function() browseForFile("open", "Choose a MIDI file", "", "*.mid;*.midi", function(task) if not task.success then return end -- dialog cancelled status.text = "Loading..." loadMidi(task.result, function(t) -- success only means the file exists: midi is nil when it is not MIDI if t.success and t.midi then sequence = t.midi status.text = string.format("%s: %d tracks, %d ticks per beat", task.result:match("[^/\\]+$"), sequence.numTracks, sequence.division) else status.text = "Not a readable MIDI file" end end) end) end setSize(400, 80) makePerformanceView()