I implemented this Average Magnitude Difference algorithm in Javascript
var abs = Math.abs
var floor = Math.floor
var POSITIVE_INFINITY = Number.POSITIVE_INFINITY
function autocorrelation (data) {
var length = data.length
var halfLength = floor(length * 0.5)
var summation = null
var smallest = POSITIVE_INFINITY
var smallestOffset = null
for (var o = 1; o < halfLength; o++) {
summation = 0
for (var i = 0; i < halfLength; i++) {
summation += abs(data[i] - data[i + o])
}
average = summation / halfLength
if (average < smallest) {
smallest = average
smallestOffset = o
}
}
return smallestOffset
}
and I use it this way
analyser.getFloatTimeDomainData(data)
var rms = rootMeanSquare(data)
var offset, frequency
if (rms > RMS_MIN) {
offset = autocorrelation(data)
frequency = SAMPLE_RATE / offset
}
to find the frequency of the signal input to the analyser.
Signal input is the output from an oscillator. The oscillator's frequency varies from C0 to B8 and I can't always detect the correct frequency. Can you tell me why, please?
Please, find below two images showing oscillator's frequencies and related detected frequencies