user1707045
user1707045

Reputation: 37

Counting fundamental frequency with yin method in C#

I need to count the fundamental frequency with yin algorithm in C#.

I have an array (data[44100]) which contains the amplitude of a 1 sec long 250Hz sinus wave. Here is my code:

int t = 0;                    //starting point of the window
int w = data.Length / 25;     //the end of the window so the size of the window is 40msec
int rmax = 0;                 //the maximum of the correlation function
int period = 0;               //the period of the sinus

for (int tau = 0; tau < w; tau++)
{ 
    int r = 0;
    for (int j = t + 1; j < (t + w); j++)
    {
       r = r + (data[j] * data[j + tau]);
    }     
    if (r > rmax)
    {
       rmax = r;
       period = tau;
    }
}

float time = (float)period/44100;
float freq = 1.0f / time;
System.Console.WriteLine(freq);

I should get 250 for the frequency but something goes wrong. The values in the array are good, i checked it in excel and the period was as it should be. Could anybody help?

Upvotes: 0

Views: 827

Answers (2)

hotpaw2
hotpaw2

Reputation: 70703

You are including a lag of zero in your autocorrelation function, and a signal correlates perfectly with itself with zero lag. You also stop (tau < w) before reaching a lag of one period, where a sin wave would have its next autocorrelation peak.

Try starting with a lag of half your expected period and stepping to 1.5x your expected period.

Upvotes: 2

Shiraz Bhaiji
Shiraz Bhaiji

Reputation: 65391

There is a mismatch between your code and your comment.

1 sec / 25 would be 0.04 sec not 0.4 sec.

Upvotes: 1

Related Questions