Advertisement
HertzDevil

How to add key signature support to your MML engine

Oct 21st, 2016
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.93 KB | None | 0 0
  1. -- MGCInts library
  2. -- this imports most modules except those in util
  3. local MGCInts = require "mgcints"
  4.  
  5. -- create a default engine with 2 channels
  6. local engine = MGCInts.Default.Engine(2, "key scale test")
  7. local macros = engine:getCommandTable()
  8. local builder = MGCInts.MML.CmdBuilder()
  9.  
  10. -- i took 3-4 hours to make this (optional arguments not shown)
  11. local notelist = engine:importFeature "keyscale"
  12.  
  13. -- build some dummy commands
  14. for k, v in notelist() do
  15.   local cmd = builder:setHandler(function (ch)
  16.     -- calling getNoteIndex is all it takes to handle accidentals
  17.     local n = ch.key:getNoteIndex(k)
  18.     ch:addChunk(("  Note: %d (%s%s)\n"):format(
  19.       60 + n, k:upper(), (n > v and "#" or "b"):rep(math.abs(n - v))))
  20.   end):make()
  21.   macros:addCommand(k, cmd)
  22.   macros:addCommand(k:upper(), cmd)
  23. end
  24.  
  25. -- channel header / footer
  26. engine.channel:beforeCallback(function (self)
  27.   self:addChunk("Channel " .. self:getID() .. ": \n")
  28. end)
  29. engine.channel:afterCallback(function (self)
  30.   self:addChunk "End of data\n\n"
  31. end)
  32.  
  33. -- test inserter, we will use a text file
  34. engine:setInserter(function (rom, song, track)
  35.   rom:write("MGCInts test\nTrack: " .. track .. "\n\n")
  36.   song:doAll(function (ch)
  37.     rom:write(ch:getStream():build())
  38.   end)
  39. end)
  40.  
  41. -- compile an MML string
  42. local mmlstr = [[
  43. !1 k-bea efgab k=a gab k+a a
  44. !2 _c+ c _c+ c | c _c+ c _c=- c
  45. ]]
  46. MGCInts.Music.Compiler.processFile(engine, mmlstr, io.stdout, 1)
  47.  
  48. -- k: key signature, applies sharps/flats to list of notes
  49. -- _: accidental, applies sharps/flats on top of key signatures
  50. -- |: bar line, resets accidentals but keeps keys
  51.  
  52. --[[ output:
  53. MGCInts test
  54. Track: 1
  55.  
  56. Channel 1:
  57.   Note: 63 (Eb)
  58.   Note: 65 (F)
  59.   Note: 67 (G)
  60.   Note: 68 (Ab)
  61.   Note: 70 (Bb)
  62.   Note: 67 (G)
  63.   Note: 69 (A)
  64.   Note: 70 (Bb)
  65.   Note: 70 (A#)
  66. End of data
  67.  
  68. Channel 2:
  69.   Note: 61 (C#)
  70.   Note: 62 (C##)
  71.   Note: 60 (C)
  72.   Note: 61 (C#)
  73.   Note: 59 (Cb)
  74. End of data
  75. ]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement