realtime_audio_visualization.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import pyaudio
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import pyaudio
  5. import wave
  6. import sys
  7. CHUNK = 1024
  8. np.set_printoptions(suppress=True) # don't use scientific notation
  9. CHUNK = 4096 # number of data points to read at a time
  10. RATE = 44100 # time resolution of the recording device (Hz)
  11. p=pyaudio.PyAudio() # start the PyAudio class
  12. stream=p.open(format=pyaudio.paInt16,channels=1,rate=RATE,input=True,
  13. frames_per_buffer=CHUNK) #uses default input device
  14. # create a numpy array holding a single read of audio data
  15. for i in range(300): #to it a few times just to see
  16. data = np.fromstring(stream.read(CHUNK),dtype=np.int16)
  17. data = data * np.hanning(len(data)) # smooth the FFT by windowing data
  18. fft = abs(np.fft.fft(data).real)
  19. fft = fft[:int(len(fft)/2)] # keep only first half
  20. freq = np.fft.fftfreq(CHUNK,1.0/RATE)
  21. freq = freq[:int(len(freq)/2)] # keep only first half
  22. freqPeak = freq[np.where(fft==np.max(fft))[0][0]]+1
  23. print("peak frequency: %d Hz"%freqPeak)
  24. # uncomment this if you want to see what the freq vs FFT looks like
  25. plt.plot(freq,fft)
  26. plt.axis([0,4000,None,None])
  27. plt.show()
  28. plt.close()
  29. # close the stream gracefully
  30. stream.stop_stream()
  31. stream.close()
  32. p.terminate()