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.