Skip to content

Instantly share code, notes, and snippets.

@CGrassin
Created April 14, 2020 17:45
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CGrassin/26a1fdf4fc5de788da9b376ff717516e to your computer and use it in GitHub Desktop.
Save CGrassin/26a1fdf4fc5de788da9b376ff717516e to your computer and use it in GitHub Desktop.
Convert a note + octave to its frequency.
# 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)
@OdysseasKr
Copy link

💯

@lafkpages
Copy link

GIves me an error:
image

@marcorentap
Copy link

did you manage to fix that? If not, can you share notes.py here?

@py660
Copy link

py660 commented Oct 2, 2022

@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.

@joaoseckler
Copy link

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