We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSound,  Music Libraries › Round frequency to the nearest semitone
Page Index Toggle Pages: 1
Round frequency to the nearest semitone (Read 1085 times)
Round frequency to the nearest semitone
Apr 29th, 2009, 5:41pm
 
Hello, I have been trying to figure out a way to round a frequency to the nearest semitone. For example, given the pitch 442Hz, it would round it to 440Hz to be a standard "A."

I'm thinking in equal temperament, but just intonation or quarter-tone scale ideas are welcome too...

EDIT:
Here's somewhat of a solution I came up with, but it's not very elegant and requires a lot of memory to work properly. There must be a better way...

Code:
// Convert to nearest midi note
float pitch = (round(69 + 12 * (log(myFreq/440.0) / log(2.0))));
pitch = 440*pow(2,(pitch-69)/12); // Convert back
Re: Round frequency to the nearest semitone
Reply #1 - Apr 29th, 2009, 11:27pm
 
In terms of generating the value math-wise each time anew, that seems right.

If avoiding the processing cost of computing those logs+exponent is really necessary, the old-school algorithm would probably be to make a lookup table of all the frequencies of equal tempered pitches, then use an optomized search algorithm (binary search, perhaps, since the array is already sorted: start in the middle, figure out which half it's in, move to that half, find which quarter it's in, etc) to find the closest existing value to a given input.

To really delve back into my college algorithms memory: for an array of N elements, finding the closest element with a binary search would take log2(N) comparisons. So if you stored 128 note values, it would take 7 comparisons to find the closest value, which is probably much faster than computing a logarithm and an exponent...but a bit more code

dan
Page Index Toggle Pages: 1