-------------------------------------------------------------------------------- --! @title NoteQuantizer --! @brief Snap Played Notes Forward to the Next Beat Subdivision --! @category MidiTools --! --! A live input quantizer: each incoming note is held back until the next line --! of the chosen grid, read from the song position with getRunningBeatTime, so --! loose playing comes out tight against the host tempo. A script cannot play a --! note earlier than it arrived, so quantizing always means delaying; notes --! played just after a grid line, within the Tolerance window, are let through --! at once instead of waiting for a whole extra step. --! --! Each note-off is delayed by the same amount as its note-on, which keeps the --! played length and guarantees the note-off never overtakes its note-on. --! --! getRunningBeatTime follows the host position while the transport runs and an --! internal clock otherwise, so the grid is there even with the host stopped. --! --! @demonstrates getRunningBeatTime, beat2ms, wait, onRelease, voice id tracking -------------------------------------------------------------------------------- local GRID_NAMES = {"1/4", "1/8", "1/8T", "1/16", "1/16T", "1/32"} local GRID_BEATS = {1, 0.5, 1 / 3, 0.25, 1 / 6, 0.125} local grid = Menu{"Grid", GRID_NAMES, selected = 4} -- Share of a step, after a grid line, still counted as "on" that line. local tolerance = Knob{"Tolerance", 0.15, 0, 0.5, unit = Unit.PercentNormalized} -- [voice id] = delay in ms applied to the note-on, reused for its note-off. local delays = {} -- Delay in ms from now to the grid line this note belongs to. local function delayToGrid() local step = GRID_BEATS[grid.value] local now = getRunningBeatTime() local sinceLine = now % step -- beats elapsed since the last grid line if sinceLine <= tolerance.value * step then return 0 -- close enough to the line just passed: play it now end return beat2ms(step - sinceLine) end function onNote(e) local delay = delayToGrid() -- The incoming event already carries the voice id its note-off will have, -- so the note-off can find the delay without any note/channel bookkeeping. delays[e.id] = delay if delay > 0 then wait(delay) end postEvent(e) end function onRelease(e) local delay = delays[e.id] delays[e.id] = nil -- A note-off with no stored delay (its note-on came before the script was -- loaded, for instance) goes through untouched. if delay and delay > 0 then wait(delay) end postEvent(e) end