Home > Tutorials > Converting a Fundamental Frequency to a Musical Note

Converting a Fundamental Frequency to a Musical Note


OK last tutorial I covered how to get a fundamental frequency from an array of audio samples by using autocorrelation, but now we will begin to look at how we can convert these frequency values to a musical note. It is actually very simple, given that notes are just incrementing frequencies, all we really need are 2 loops, an octave loop and a note loop. In the octave loop we times our base frequency by 2 every loop, because each octave denotes a doubling of pitch, and in our note loop we times our testing frequency by 1.05946, which is the equal temperament of western music, it is also the twelfth root of 2, which is important considering there are essential '12' frequencies we are looking for in each octave (inclusive of accidentals):

-(BOOL) getNote:(double)fundamentalFrequency
{
	double baseFreq = 65.406; // C2
	for(int i=2;i<6;i++)
	{
		double testFreq = baseFreq;
		for(int j=0;j<12;j++)
		{
			double nextFreq = testFreq * 1.05946; // Equal Temperment;
			double lastFreq = testFreq / 1.05946;
			if(fundamentalFrequency > lastFreq && fundamentalFrequency < nextFreq)
			{
				double nextPercDif = (fundamentalFrequency - testFreq) / (nextFreq - testFreq);
				double lastPercDif = (fundamentalFrequency - lastFreq) / (testFreq - lastFreq);
				if(nextPercDif <= 0.5 && lastPercDif >= 0.5)
				{
					octave = i;
					natural = 0;
					switch(j)
					{
						case 0: note = 0; natural = 0; break;
						case 1: note = 0; natural = 1; break;
						case 2: note = 1; natural = 0; break;
						case 3: note = 1; natural = 1; break;
						case 4: note = 2; natural = 0; break;
						case 5: note = 3; natural = 0; break;
						case 6: note = 3; natural = 1; break;
						case 7: note = 4; natural = 0; break;
						case 8: note = 4; natural = 1; break;
						case 9: note = 5; natural = 0; break;
						case 10: note = 5; natural = 1; break;
						case 11: note = 6; natural = 0; break;
					}
					return true;
				}
			}
			testFreq = nextFreq;
		}
		baseFreq *= 2.0;
	}
	return false;
}

This code is assuming octave, note and natural are global variables in whatever class this function is included in. If we look at Wikipedia's Musical Note page under the heading "Note designation in accordance with octave name" we can see the frequency values of each note, this gives us an idea of how our loop is working. To convert the note number to it's formal musical name, we just simple have to have a lookup table (I use defines personally):

#define A 5
#define B 6
#define C 0
#define D 1
#define E 2
#define F 3
#define G 4

And now we have converted our fundamental frequency into musical notation information, giving us the octave, the note name and whether or not it is a sharp (or accidental).

Author: admin Categories: Tutorials Tags:
  1. No comments yet.
  1. No trackbacks yet.