From 7f7445eb64d8e0b46fafa9e55e6cf55ac046239d Mon Sep 17 00:00:00 2001 From: Nicolas Mafra Date: Wed, 31 Jan 2024 18:54:10 -0300 Subject: [PATCH] feat: add PitchParser --- theory/PitchParser.mjs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 theory/PitchParser.mjs diff --git a/theory/PitchParser.mjs b/theory/PitchParser.mjs new file mode 100644 index 0000000..c511829 --- /dev/null +++ b/theory/PitchParser.mjs @@ -0,0 +1,27 @@ +const notes = [ 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B' ]; + +export default { + chromaToText(chroma) { + return notes[chroma]; + }, + textToChroma(text) { + const letter = text.substring(0, 1); + let chroma = notes.indexOf(letter); + if (text.includes('#')) chroma++; + if (text.includes('b')) chroma--; + return (chroma + 12) % 12; + }, + pitchToText(midiNumber) { + const chroma = midiNumber % 12; + const octave = Math.floor(midiNumber / 12) - 1; + + return this.chromaToText(chroma) + octave; + }, + textToPitch(text) { + const chroma = this.textToChroma(text); + text = text.substring(1); + if (text.startsWith('#') || text.startsWith('b')) text = text.substring(1); + const octave = parseInt(text); + return 12 * (octave + 1) + chroma; + }, +};