Converting Sound Frequency to Musical Pitch Notation
Using Python to have code output musical pitch notation based on sound frequencies.
Join the DZone community and get the full member experience.Join For Free
how can you convert the frequency of a sound to musical notation? i wrote in an earlier post how to calculate how many half steps a frequency is above or below middle c, but it would be useful go further have code to output musical pitch notation.
in scientific pitch notation , the c near the threshold of hearing, around 16 hz, is called c0. the c an octave higher is c1, the next c2, etc. octaves begin with c; other notes use the octave number of the closest c below.
the lowest note on a piano is a0, a major sixth up from c0. middle c is c4 because it’s 4 octaves above c0. the highest note on a piano is c8.
a4, the a above middle c, has a frequency of 440 hz. this is nine half steps above c4, so the pitch of c4 is 440*2 -9/12 . c0 is four octaves lower, so it’s 2 -4 = 1/16 of the pitch of c4. (details for this calculation and the one below are given in here .)
for a pitch p, the number of half steps from c0 to p is h = 12 log 2 ( p / c0).
the python code below calculates the number of half steps h from c0 up to a pitch, then computes the corresponding pitch notation.
from math import log2, pow a4 = 440 c0 = a4*pow(2, -4.75) name = ["c", "c#", "d", "d#", "e", "f", "f#", "g", "g#", "a", "a#", "b"] def pitch(freq): h = round(12*log2(freq/c0)) octave = h // 12 n = h % 12 return name[n] + str(octave)
the pitch for a4 is its own variable in case you’d like to modify the code for a different tuning. while 440 is common, it used to be lower in the past, and you’ll sometimes see higher values like 444 today.
if you’d like to port this code to a language that doesn’t have a
function, you can use
powers of 2
when scientific pitch notation was first introduced, c0 was defined to be exactly 16 hz, whereas now it works out to around 16.35. the advantage of the original system is that all c’s have frequency a power of 2, i.e. c n has frequency 2 n +4 hz. the formula above for the number of half steps a pitch is above c0 simplifies to h = 12 log 2 p – 48.
if c0 has frequency 16 hz, the a above middle c has frequency 2 8.75 = 430.54, a little flat compared to a 440. but using the a 440 standard, c0 = 16 hz is a convenient and fairly accurate approximation.
Published at DZone with permission of John Cook, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.