Do I have to use FFT?

Hello everyone, this question is not entirely about Defold, but Lua herself. I wrote it here because Defold has a great community and I create my application in Defold.
So to the point. I want to calculate the frequency of an audio track so I can program something like a tuner. I use this code to get the audio amplitudes:

f = assert(io.open("C:\\Users\\karel\\downloads\\mono.wav", "rb"))
f:seek("cur", 48)

while true do
bytes = f:read(1)
if not bytes then print(count) break end

b = string.byte(bytes, 1, -1)
b = string.format("%02x", b)
bytes = f:read(1)
b1 = string.byte(bytes, 1, -1)
b1 = string.format("%02x ", b1)

x = b .. b1
x = tonumber(x, 16)

if x ~= 0 then
x = x - 32768
end

print(x)
f:seek("cur", 2)
end

The result is exactly what I want, so each amplitude of sound 44110 times per second. A small example:

DEBUG:SCRIPT: -22784
DEBUG:SCRIPT: -25088
DEBUG:SCRIPT: -27392
DEBUG:SCRIPT: -29952
DEBUG:SCRIPT: -32256
DEBUG:SCRIPT: 31231
DEBUG:SCRIPT: 29439
DEBUG:SCRIPT: 27903

At the same time, I know that a simple formula is enough to calculate the frequency of sound: f = 1 / T. I would really like to calculate it like this without using a complex FFT, but I don’t know how to find the period (duration) of a sound wave, from which I would simply calculate [T], ie the duration of one wave. But I don’t know how to find the beginning and end of a wave. I thought that where there is zero, the wave begins or ends, but somehow it doesn’t work out. Maybe I’m wrong. So I need advice on how to easily find out the wave period and if it is even possible to do without FFT. I will be grateful for any answer.

And I should add that I don’t want to use libraries. I want to learn how to do it and have my own code.

It’s a really specialised question :confused: I would try to search for how to find periods/frequencies of the wave without using FFT, but from what I learned in college, it will be surely an estimation only, but it could be enough for you. And there will be of course a lot of frequencies in the analysed wave, so maybe that’s a problem with zero crossings (as there is a lot of them and not particularly two neighbouring places are representing one period). Guys below tried to find it that way:

If it won’t be enough I would go with FFT anyway, it’s the best solution known to me :wink: Check:

https://luarocks.org/modules/h4rm/luafft

3 Likes

Thank you very much, I’ll study it right away.

2 Likes

I don’t know much about this but I know it’s gonna be a big challenge. You’re gonna need an algorithm to calculate wavelength, or calculate an average over a length of time. Basically, you’re going to need FFT…

2 Likes