In [1]:
# I know how to do this with Julia off the top of my head, BUT
# If you used Python and numpy.fft, surely there would be a sound loading library you could find.
using FFTW
using Plots
In [2]:
# Let's make a sample of a square wave because it's easy.
n = 256
x = ones(n)
x[1:n÷2] .= -1
# Note: A "perfect" square wave has zero crossings at the same place as a sin wave
# Not important for audio, but makes the coefficients come out to 0 later on.
x[[1,n÷2+1]] .= 0
# Plot out a few repetitions of our wave.
plot([x; x; x]; size=(1200, 200))
Out[2]:
In [3]:
# The signal x only has real numbers (no imaginary part).
# A full FFT would produce duplicate values, and they aren't useful to output a real valued signal anyway.
# Instead just take the real-valued FFT or rfft.
X = rfft(x)
plot([real(X), imag(X)], labels=["real" "imag"])
Out[3]:
In [4]:
# These are the spectral numbers that PeriodicWave wants.
# The phase of the original wave is 0, so all the "real" numbers are zero.
# You might need to rescale them though, nobody can agree on what the scaling factor of a fourier transform should be. (shrug)
round.(X, digits=3)
Out[4]:
129-element Vector{ComplexF64}: 0.0 + 0.0im -0.0 + 162.966im 0.0 + 0.0im 0.0 + 54.3im 0.0 + 0.0im -0.0 + 32.554im 0.0 - 0.0im 0.0 + 23.225im 0.0 + 0.0im -0.0 + 18.035im 0.0 + 0.0im -0.0 + 14.726im 0.0 + 0.0im ⋮ -0.0 + 0.272im 0.0 - 0.0im 0.0 + 0.222im 0.0 - 0.0im 0.0 + 0.172im 0.0 + 0.0im -0.0 + 0.123im 0.0 + 0.0im -0.0 + 0.074im 0.0 - 0.0im 0.0 + 0.025im 0.0 + 0.0im
In [5]:
# When you take the inverse fourier transform, you reproduce the original signal
# This is what PeriodicWave is doing.
x2 = irfft(X, n)
plot([x2; x2; x2], size=(1200,200))
Out[5]:
In [6]:
# So... this is kind of what I was getting at.
# If you have a sample of a wave, you can easily get it's spectra with a real valued fourier transform.
# If you have the sample, then why bother going to the effort to convert it to the spectra?
# The first thing PeriodicWave does is to change it back to the original sample you _already_ had.