Skip to content

Instantly share code, notes, and snippets.

@hosackm
Created June 21, 2016 04:27
Show Gist options
  • Save hosackm/8531ec37044fe58dd46d4c3b51531664 to your computer and use it in GitHub Desktop.
Save hosackm/8531ec37044fe58dd46d4c3b51531664 to your computer and use it in GitHub Desktop.
FFT plot of 440 Hz sine tone in numpy
import numpy as np
import scipy.io.wavfile as wf
import matplotlib.pylab as plt
def main():
# use power of 2 for FFT length
FFTN = 2**14
try: # try to read from wav file
_, y = wf.read("test.wav")
except: # generate the signal if it doesn't exist
FS = 48000.
N = FS * 3
y = np.sin(2. * np.pi * 440 * np.arange(N) / FS)
# read a chunk of the signal and apply hanning window
y1 = y[:FFTN] * np.hanning(FFTN)
# plot the signal to verify it's correct
plt.plot(y1)
plt.show()
# take first half of the FFT because the second half is a mirror image
Y = np.fft.fft(y1)[:FFTN//2]
# convert to SPL in dB and calculate frequency scale
SPL = 10 * np.log10(abs(Y)**2)
FBINS = np.linspace(0., 24000., len(SPL))
# plot the intensity
plt.semilogx(FBINS, SPL)
plt.show()
# take first value in list, * in case it's a list of length 1
maxf, *_ = FBINS[SPL == max(SPL)]
print("Peak detected at:", maxf, "Hz")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment