audio_visualize_1.py 1.0 KB

123456789101112131415161718192021222324252627282930
  1. def audio_visualize_1d(self):
  2. xf = np.linspace(20, self.rate / 2, self.window)
  3. fig, ax = plt.subplots(figsize=(14, 5))
  4. lf, = ax.semilogx(xf, np.zeros(self.window), lw=1, color='lightblue')
  5. ax.set_ylim(-0.5, 1.5)
  6. ax.set_axis_off()
  7. plt.show(block=False)
  8. plt.pause(self.record_delay)
  9. while self.stream.is_active():
  10. data = self.stream.read(self.window)
  11. data_int = struct.unpack(str(self.window * 2) + 'B', data)
  12. y_detrend = detrend(data_int)
  13. box = np.ones(self.fwhm) / self.fwhm
  14. y_smooth = np.convolve(y_detrend, box, mode='same')
  15. yft = np.abs(np.fft.fft(y_smooth))
  16. y_vals = yft[:self.window] / (64 * self.window)
  17. ind = np.where(y_vals > (np.max(y_vals) + np.min(y_vals)) / 2)
  18. y_vals[ind[0]] *= 4
  19. lf.set_ydata(y_vals)
  20. try:
  21. ax.figure.canvas.draw()
  22. ax.figure.canvas.flush_events()
  23. except TclError:
  24. self.stream.stop_stream()
  25. self.stream.close()
  26. break