Skip to content

Instantly share code, notes, and snippets.

@nhthn
Created February 10, 2019 18:29
Show Gist options
  • Save nhthn/e9dcaed33ad7780c620ba6b60ed2193f to your computer and use it in GitHub Desktop.
Save nhthn/e9dcaed33ad7780c620ba6b60ed2193f to your computer and use it in GitHub Desktop.
MiniPond
/*
MiniPond is a tiny variant of the LilyPond note entry syntax.
cdefgab - note name
s - sharp
f - flat
' - octave up
, - octave down
4 - quarter note
2 - half note
1 - whole note
4. - dotted quarter note
4.. - double dotted quarter note
~ - tie to next note
Octaves are absolute, not relative.
*/
MiniPond {
*parse { |string|
var noteStrings, events, lastDuration, lastWasATie;
noteStrings = string.replace($\n, " ").stripWhiteSpace.split($ );
events = List[];
lastDuration = "4";
lastWasATie = false;
noteStrings.do { |noteString|
var match;
var degree, accidental, octave, duration, dots, tie;
var midiNote, quarterNotes;
match = noteString.findRegexp("^([cdefgab]?)([fs]?)([',]*)(\\d*)(\\.*)(~?)$");
match.isEmpty.if {
Error("bad note string %".format(noteString)).throw;
};
degree = match[1][1];
accidental = match[2][1];
octave = match[3][1];
duration = match[4][1];
dots = match[5][1];
tie = match[6][1];
degree = "cdefgab".indexOf(degree[0]) ? 0;
accidental = ['f', '', 's'].indexOf(accidental.asSymbol) - 1;
octave = octave.as(Array).collect({ |char| if(char == $', 1, -1) }).sum;
duration.isEmpty.if { duration = lastDuration };
lastDuration = duration;
duration = duration.asInteger;
dots = dots.size;
tie = tie.notEmpty;
midiNote = 60 + Scale.major[degree] + accidental + (octave * 12);
quarterNotes = 4 / duration * (2 - pow(0.5, dots));
lastWasATie.if {
events.last[\dur] = events.last[\dur] + quarterNotes;
} {
events.add((dur: quarterNotes, midinote: midiNote));
};
lastWasATie = tie;
};
^events;
}
*durations { |string|
^MiniPond.parse(string).collect(_[\dur]);
}
*pitches { |string|
^MiniPond.parse(string).collect(_[\midinote]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment