Skip to content

Instantly share code, notes, and snippets.

@mauritslamers
Created April 26, 2015 21:55
Show Gist options
  • Select an option

  • Save mauritslamers/bce4ed985615199f1876 to your computer and use it in GitHub Desktop.

Select an option

Save mauritslamers/bce4ed985615199f1876 to your computer and use it in GitHub Desktop.
var newFFTPitch = {
calc: function (fft, samplerate, fftSize) {
var fftLen = fft.length;
var i;
var max = fft[0];
var curVal;
for (i=1; i < fftLen; i += 1) {
curVal = fft[i];
if (curVal > max) max = curVal;
}
// now find the index of 1/3
var leastIndex = -1;
var minVal = max / 3;
var leastVal = max;
for (i = 0; i < fftLen; i += 1) {
curVal = fft[i];
if (curVal > minVal && curVal < leastVal) {
leastVal = curVal;
leastIndex = i;
}
}
var prevIndex = leastIndex - 1;
var nextIndex = leastIndex + 1;
var prevVal = fft[prevIndex];
var nextVal = fft[nextIndex];
/*
// https://ccrma.stanford.edu/~jos/parshl/Peak_Detection_Steps_3.html#sec:peakdet
explanation uses alpha for prevVal, beta for leastVal, gamma for nextVal
then gives 1/2 * ( (alpha - gamma) / (alpha - 2*beta + gamma) )
for the parabole peak location, which is the position it would have in the array
the frequency would be (sampleFreq*p)/ fftsize ?
*/
var p = 1/2 * ( (prevVal-nextVal) / (prevVal - (2*leastVal) + nextVal));
var freq = (samplerate * (p + leastIndex)) / fftSize;
console.log('freq: ' + freq);
return freq;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment