So i'm working on a guitar tuner app, and i'm struggling to get my head fully around using FFTs to find base frequency. here's my code for "trying" to find frequency from PCM sound array data[], size 4160 (bufferSize), sampling rate of 8000 Hz
DoubleFFT_1D fft1d = new DoubleFFT_1D(bufferSize);
double[] fftBuffer = new double[bufferSize*2];
double[] magnitude = new double[bufferSize/2];
// copy real input data to complex FFT buffer
for(int i = 0; i < bufferSize-1; ++i){
fftBuffer[2*i] = data[i];
fftBuffer[2*i+1] = 0;
}
//perform FFT on fft[] buffer
fft1d.realForward(fftBuffer);
// calculate power spectrum (magnitude) values from fft[]
for(int i = 0; i < (bufferSize/2)-1; ++i) {
double real = (2 * fftBuffer[i]);
double imaginary = (2 * fftBuffer[i] + 1);
magnitude[i] = Math.sqrt( real*real + imaginary*imaginary );
}
// find largest peak in power spectrum
for(int i = 0; i < (bufferSize/2)-1; ++i) {
if(magnitude[i] > maxVal){
maxVal = (int) magnitude[i];
binNo = i;
}
}
// convert index of largest peak to frequency
freq = 8000 * binNo/bufferSize;
Most of this is based off of examples and answers found to similar questions on this site, so my understanding of it all is a little sketchy at best.
While testing my program using a pitch generator, the frequency value coming back seems to vary massively.
I'm wondering if there's any obvious flaws here in my code, or my understanding of the process, and any pointer in the right direction