signal processing – How to extract top frequency of a graph with FFT javascript
I’m using an FFT JS library (github.com/indutny/fft.js/) to extract frequencies from line graph data that get new data points every second.
This is my code:
function getFrequencis(frequencySpectrum, sampleRate, dataLength) {
const binSize = sampleRate / dataLength;
var frequenciesDict = {}
for (let j = 1; j < frequencySpectrum.length; j++) {
frequenciesDict[j*binSize] = frequencySpectrum[j]
}
return frequenciesDict
}
const f = new FFT(32);
const out = f.createComplexArray();
f.realTransform(out, [1,2,3,4,5,5,4,3,2,1,1,2,3,4,5,5,4,3,2,1,1,2,3,4,5,5,4,3,2,1,2,3]);
getFrequencis(out, 1, 32)
I expect to find that the 0.1 frequency is the strongest, but this is the response I get:
{
"1": -1,
"0.03125": 0,
"0.0625": -1.330508935085469,
"0.09375": -0.5060331130932036,
"0.125": -2.7653668647301792,
"0.15625": -2.082392200292394,
"0.1875": -17.666465995914333,
"0.21875": -21.984229521692033,
"0.25": 3.82842712474619,
"0.28125": 8.242640687119286,
"0.3125": 0.947624077129027,
"0.34375": 4.812059092662567,
"0.375": -0.15224093497742652,
"0.40625": 3.613125929752753,
"0.4375": -0.7634026789260374,
"0.46875": 2.773999558787147,
"0.5": -1,
"0.53125": 2,
"0.5625": -0.3599059628302478,
"0.59375": 1.0688810757972436,
"0.625": -3.8477590650225735,
"0.65625": 1.6131259297527532,
"0.6875": -2.2684947746976585,
"0.71875": 0.6627612703477461,
"0.75": -1.82842712474619,
"0.78125": 0.24264068711928477,
"0.8125": -1.4979446807556052,
"0.84375": 0.008608279724096946,
"0.875": -1.2346331352698205,
"0.90625": -0.0823922002923938,
"0.9375": -1.0609010489196744,
"0.96875": -0.06901597235215756,
"1.03125": 0,
"1.0625": -0.41421356237309515,
"1.09375": 0.1715728752538097,
"1.125": 0,
"1.15625": 0,
"1.1875": 2.414213562373096,
"1.21875": -5.82842712474619,
"1.25": -4,
"1.28125": 0,
"1.3125": -3,
"1.34375": 0,
"1.375": 7,
"1.40625": 0,
"1.4375": 3,
"1.46875": 0,
"1.5": 25,
"1.53125": 0,
"1.5625": 0.8786796564403576,
"1.59375": 0.2928932188134523,
"1.625": 0,
"1.65625": 1,
"1.6875": 5.121320343559643,
"1.71875": -1.7071067811865475,
"1.75": -5,
"1.78125": 0,
"1.8125": -1,
"1.84375": 0,
"1.875": 8,
"1.90625": 0,
"1.9375": 2,
"1.96875": 0
}
Two questions:
- why 0.09375 frequency is not the strongest amplitude?
- Why do I get negative amplitudes if the graph is only positive?
Thanks!
Read more here: Source link
