Created
April 14, 2020 17:45
-
-
Save CGrassin/26a1fdf4fc5de788da9b376ff717516e to your computer and use it in GitHub Desktop.
Convert a note + octave to its frequency.
This file contains hidden or 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
# MIT License | |
# Python to convert a string note (eg. "A4") to a frequency (eg. 440). | |
# Inspired by https://gist.github.com/stuartmemo/3766449 | |
def getFrequency(note, A4=440): | |
notes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] | |
octave = int(note[2]) if len(note) == 3 else int(note[1]) | |
keyNumber = notes.index(note[0:-1]); | |
if (keyNumber < 3) : | |
keyNumber = keyNumber + 12 + ((octave - 1) * 12) + 1; | |
else: | |
keyNumber = keyNumber + ((octave - 1) * 12) + 1; | |
return A4 * 2** ((keyNumber- 49) / 12) |
did you manage to fix that? If not, can you share notes.py here?
@lafkpages I think you need to include two characters, the note name and the octave, otherwise the program would have no idea which octave to use.
Alternatively,
NOTES = ['A', 'Bb', 'B', 'C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab']
def pitch2freq(pitch, A4=440):
note = NOTES.index(pitch[:-1])
octave = int(pitch[-1])
distance_from_A4 = note + 12 * (octave - (4 if note < 3 else 5))
return A4 * 2 ** (distance_from_A4/12)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
💯