# Getting my Calc Wrong?

I am trying to calculate the correct Hertz out of a sound, the sound i am playing is a 500hz Test Tone.
i am getting an output value of 7.69344481454937E-08

can any one see where i am going wrong in my code?

``````public void UpdateOne()
{
float max = 0.0f;

if(!source.isPlaying)
return;

AudioListener.GetSpectrumData(anlyData.Bin, 0,FFTWindow.BlackmanHarris);

for(int i=0; i < anlyData.NbSamples; i++)
{
if(Mathf.Abs(anlyData.Bin*)> max)*
``````
• ``````  	{*
``````
• ``````  		int Value1 = (AudioSettings.outputSampleRate/2)/anlyData.NbSamples;*
``````

float Value2 = this.Clamp(anlyData.Bin * 2.0f, 0.0f, (float)AudioSettings.outputSampleRate);
* max = Value2 / Value1;*
* }*
* }*
* }*

* public float Clamp (float value, float min, float max)*
* {*
if(value < min)
value = min;
if(value > max)
value = max;
return value;
* }*
* public void CalculateAvg()*
* {*
* float AvgFreq = 0.0f;*

_ /* work out mean /_
_
for(int i= 0; i < anlyData.MaxPeak.Count; i++)_
_ AvgFreq += (float)anlyData.MaxPeak;*_

_ /* Text display /
infoFreq.text = "Avg Freq: "+AvgFreq;
}*_

You’ve started very well, using BlackmanHarris window and outputSampleRate to find the sample frequency, but the frequency calculation was wrong. You must find the max value and save its bin index. This bin index multiplied by the frequency resolution (outputSampleRate/2/NbSamples) gives the dominant frequency. In order to improve the result, you can interpolate the bin number using the two nearest neighbors. The modified code is:

```    ...
AudioListener.GetSpectrumData(anlyData.Bin, 0,FFTWindow.BlackmanHarris);
int bin = 0;
for(int i=0; i < anlyData.NbSamples; i++)
{
if (anlyData.Bin *> max) // the bin values are in the (0..1) range*
*{*
_max = anlyData.Bin*; // find the max amplitude*_
_*bin = i;               // and save its bin index*_
_*}*_
_*}*_
_*float binF = bin;  // interpolate the bin number with neighbors*_
_*if (bin>0 && bin<anlyData.NbSamples-1){*_
_*float dL = anlyData.Bin[bin-1]/max; // left neighbor weight*_
_*float dR = anlyData.Bin[bin+1]/max; // right neighbor weight*_
_binF += 0.5*(dR*dR - dL*dL); // simple quadratic interpolation_
_*}  // calculate the frequency*_
_float frequency = binF*(AudioSettings.outputSampleRate/2)/anlyData.NbSamples;_