I am trying to get the fundamental frequency of a signal that only has a single pitch. I coded out the autocorrelation function using FFT and already got the autocorrelation result. Unfortunately, I don't know how to get the fundamental frequency from the autocorrelation result. Can someone help me? My code is below:
public double getPitch(double[] buffer, int firstSample, int lastSample, double sampleRate)
{
int lengthOfFFTWindow=lastSample-firstSample;
double[] input_buffer=new double[lengthOfFFTWindow];
DoubleFFT_1D fft = new DoubleFFT_1D(lengthOfFFTWindow);
double[] autocorrelation_values=new double[lengthOfFFTWindow];
double[] fftData = new double[lengthOfFFTWindow * 2];
double max=-1;
double max_i=-1;
//FFT on each sample in each window
for (int i = 0; i < lengthOfFFTWindow; i++) {
// copying audio data to the fft data buffer, imaginary part is 0
fftData[2 * i] = buffer[i+firstSample];
fftData[2 * i + 1] = 0;
}
fft.complexForward(fftData);
for (int i = 0,j=0; i < fftData.length; i += 2,j++) {
// complex numbers -> vectors, so we compute the length of the vector, which is sqrt(realpart^2+imaginarypart^2)
autocorrelation_values[j] = Math.sqrt((fftData[i] * fftData[i]) + (fftData[i + 1] * fftData[i + 1]));
}
fft.complexInverse(fftData, false);
for(int i=0;i<fftData.length;i++)
{
if(max<fftData[i])
{
max=fftData[i];
max_i=i;
}
}
return (max_i * 44100 )/ lengthOfFFTWindow;
}
Is it correct to return the maximum autocorrelation value divide by 2 as the fundamental frequency? I keep getting wrong answers when I do that.
EDIT: An example of the single pitch test file: http://dl.dropbox.com/u/24274475/testfile_A4.wav