Created
May 20, 2024 03:54
-
-
Save hsingtism/533179a82898570d7e8629528bcf2e84 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Function that converts scientific pitch notation (American standard pitch notation or international pitch notation) | |
to a frequency. Input must pass noteToPitch.validate else function may not work as intended. | |
First character must be an uppercase letter of the note A-G. Follows is | |
'#' for sharp and 'b' for flat. Although not standard, these flat and sharp | |
modifiers may be stacked infinitely. The octave number follows; it can be any integer. | |
All pitch is equal temperament at A440. The pitch of standard A can be trivially | |
changed. | |
Example: | |
'A4' returns 440, standard A | |
'Ab#4' returns 440, A flat sharp 4, equivlent standard A | |
'G##4' returns 440, G double sharp 4, equivlent standard A | |
'C4' returns 261.6255653005986, middle C | |
'Bb6' returns 1864.6550460723597, B flat 6 | |
'C-1' returns 8.175798915643707, it is one octave lower than C0 | |
*/ | |
const noteToHz = note => 440 * 2 ** ( | |
("C-D-EF-G-A-B".indexOf(note[0]) + (note.match(/#/g) || []).length - (note.match(/b/g) || []).length - 9) / 12 | |
+ (Number((note.match(/\d|-/g) || ['4']).join('')) - 4) | |
) | |
noteToHz.validate = s => /^[A-G][#b]*-?\d*$/g.test(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment