diff options
-rw-r--r-- | applause.lua | 31 |
1 files changed, 20 insertions, 11 deletions
diff --git a/applause.lua b/applause.lua index dd0ea56..ae92e02 100644 --- a/applause.lua +++ b/applause.lua @@ -1732,6 +1732,9 @@ end -- MIDI primitives do + local band = bit.band + local floor, log = math.floor, math.log + local note_names = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" @@ -1740,8 +1743,8 @@ do -- MIDI note number to name -- NOTE: mton() can handle the words as generated by MIDINoteStream function mton(note) - note = bit.band(note, 0xFF) - local octave = math.floor(note / 12)-1 + note = band(note, 0xFF) + local octave = floor(note / 12)-1 return note_names[(note % 12)+1]..octave end @@ -1762,9 +1765,7 @@ do end function Stream:ntom() return self:map(ntom) end -end -do -- There are only 128 possible MIDI notes, -- so their frequencies can and should be cached. -- We do this once instead of on-demand, so the lookup @@ -1778,19 +1779,27 @@ do -- Convert from MIDI note to frequency -- NOTE: mtof() can handle the words as generated by MIDINoteStream function mtof(note) - return mtof_cache[bit.band(note, 0xFF)] + return mtof_cache[band(note, 0xFF)] end function Stream:mtof() return self:map(mtof) end -end --- Convert from frequency to closest MIDI note -function ftom(freq) - -- NOTE: math.log/2 is a LuaJIT extension - return math.floor(12*math.log(freq/440, 2) + 0.5)+69 + -- Convert from frequency to closest MIDI note + function ftom(freq) + -- NOTE: math.log/2 is a LuaJIT extension + return floor(12*log(freq/440, 2) + 0.5)+69 + end + + function Stream:ftom() return self:map(ftom) end end -function Stream:ftom() return self:map(ftom) end +-- Convert from MIDI name to frequency +function ntof(name) return mtof(ntom(name)) end +function Stream:ntof() return self:map(ntof) end + +-- Convert from frequency to closest MIDI note name +function fton(freq) return mton(ftom(freq)) end +function Stream:fton() return self:map(fton) end -- Tick an instrument only when an inputstream (note_stream), -- gets ~= 0. When it changes back to 0 again, an "off"-stream |