This project has moved. For the latest updates, please go here.

Noob question/issue with NAudio and FFT

May 24, 2012 at 1:07 PM

 

Hi guys,

I don't know much about audio but I decided to try and figure out how to make a guitar tuner. 

I used some of Mark's code to create a sine wave and calculate the frequency with an FFT. I have a couple of issues with the code below.

1. I'm not getting the right frequency back.  I input 440 and get back 298.

2. it takes forever to calculate.  10-20 seconds

Clearly I'm doing one or more things wrong.  Any help would be appreciated.

Thanks,

Erik

 

           int sampleRate = 44100;
            double amplitude = 0.25 * short.MaxValue;
            double frequency = Double.Parse(textBox1.Text);
            Complex[] myComplexBuff = new Complex[44100];
            for (int n = 0; n < buffer.Length; n++)
            {
                buffer[n] = (short)(amplitude * Math.Sin((2 * Math.PI * n * frequency) / sampleRate));
                myComplexBuff[n].X = (float)buffer[n] / short.MaxValue;
                myComplexBuff[n].Y = 0;
            }
            //sampleRate = 4096;
            int frames = 1024;
            for (int i =0; i< frames;i++)
            {
                    myComplexBuff[i].X = myComplexBuff[i].X * (float)FastFourierTransform.HammingWindow(i, frames);
                
            }
            FastFourierTransform.FFT(true, frames, myComplexBuff);
           
            float binSize = sampleRate / frames;
            int minBin = (int)(85 / binSize);
            int maxBin = (int)(300 / binSize);

            float maxIntensity = 0f;
            int maxBinIndex = 0;

            for (int bin = minBin; bin <= maxBin; bin++)
            {
                float real = myComplexBuff[bin].X;
                float imaginary = myComplexBuff[bin].Y;
                float intensity = real * real + imaginary * imaginary;
                if (intensity > maxIntensity)
                {
                    maxIntensity = intensity;
                    maxBinIndex = bin;
                }

            }
            float freq = binSize * maxBinIndex;
            Debug.WriteLine(freq);
            textBlock1.Text = freq.ToString();

 


Coordinator
May 25, 2012 at 9:00 AM

FFT is not quick, and is quite difficult to get your head round if you are new to signal processing.

I wrote an article discussing FFT with NAudio in some detail here:

http://channel9.msdn.com/coding4fun/articles/AutotuneNET

May 25, 2012 at 11:50 AM

Thanks Mark.  I've read your article on autotune but it appears I need to read it again and more.  :).  I'll keep plugging away.