I'm writing an app in which I need to find the fundamental frequency of a note produced by a trombone. To do this I'm taking the FFT of audio data from a microphone and then using autocorrelation code taken from this question.
Once I've done that I'm then attempting to find the fundamental frequency by finding the highest and second highest peak locations and how many samples they are apart. I then find the amount of time one sample lasts with a sampling rate of 44100 and multiply that by the number of samples between the two peaks to give me the period of the fundamental frequency. Finally I use 1/period to find the fundamental frequency itself. Here's the code I've written for that (in Java):
public double findFundamentalFrequency(double[] autoCorrelatedData){
double max = Integer.MIN_VALUE;
double secondMax = Integer.MIN_VALUE;
int maxLoc = Integer.MIN_VALUE;
int secondMaxLoc = Integer.MIN_VALUE;
for(int i = 0; i < autoCorrelatedData.length; i++){
if(autoCorrelatedData[i] > max){
secondMaxLoc = maxLoc;
secondMax = max;
max = autoCorrelatedData[i];
maxLoc = i;
}
else if(autoCorrelatedData[i] > secondMax){
secondMax = autoCorrelatedData[i];
secondMaxLoc = i;
}
}
double samplingPeriod = 1/44100.0;
//Log.i("a", String.valueOf(maxLoc));
//Log.i("b", String.valueOf(secondMaxLoc));
double period = samplingPeriod * Math.abs(maxLoc - secondMaxLoc);
double fundamentalFreq = 1.0/period;
return fundamentalFreq;
}
Is this the correct way to find the fundamental frequency using autocorrelation? The answers this gives seem to be incorrect so I'm unsure if I've made a mistake somewhere or if I'm going about this the wrong way.