Python RGB Matrix games and animations https://www.xythobuz.de/ledmatrix_v2.html
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

audio.py 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python3
  2. # ----------------------------------------------------------------------------
  3. # "THE BEER-WARE LICENSE" (Revision 42):
  4. # <xythobuz@xythobuz.de> wrote this file. As long as you retain this notice
  5. # you can do whatever you want with this stuff. If we meet some day, and you
  6. # think this stuff is worth it, you can buy me a beer in return. Thomas Buck
  7. # ----------------------------------------------------------------------------
  8. import time
  9. import pyaudio
  10. import numpy as np
  11. class AudioVisualizer:
  12. def __init__(self, g, f = 20, t = 60.0):
  13. self.gui = g
  14. self.interval = 1.0 / f
  15. self.timeout = t
  16. self.chunk = 1024 * 2 # stereo
  17. self.do_fft = False
  18. self.p = pyaudio.PyAudio()
  19. self.s = self.p.open(format=pyaudio.paInt16, channels=2, rate=44100, input=True)
  20. print(self.s)
  21. def restart(self):
  22. self.data = self.init()
  23. self.start = time.time()
  24. def finished(self):
  25. if (time.time() - self.start) >= self.timeout:
  26. return True
  27. return FALSE
  28. def draw_line(self, x, val, y_off):
  29. h = int(val) / 32768.0 * self.gui.height / 2
  30. self.gui.set_pixel(x, y_off + (16 - h), (255, 255, 255))
  31. def draw_bar(self, x, val, y_off):
  32. h = int(val) / (32768.0 * 2) * (self.gui.height / 2)
  33. for y in range(0, int(h)):
  34. self.gui.set_pixel(x, y_off + (32 - y), (255, 255, 255))
  35. def draw(self):
  36. frames = self.s.read(self.chunk)
  37. left = frames[::4] # start from first left sample (index 0), skip 4 bytes (2 * 2, int16 and stereo)
  38. left = np.frombuffer(left, dtype=np.int16)
  39. right = frames[2::4] # start from first right sample (index 2), skip 4 bytes
  40. right = np.frombuffer(right, dtype=np.int16)
  41. if self.do_fft:
  42. # FFT
  43. left = np.fft.fft(left)
  44. right = np.fft.fft(right)
  45. # average down to fit screen
  46. m = self.chunk / 2 / self.gui.width # stereo
  47. left = left.reshape(-1, int(m)).mean(axis=1)
  48. right = right.reshape(-1, int(m)).mean(axis=1)
  49. for x in range(0, self.gui.width):
  50. if self.do_fft:
  51. self.draw_bar(x, left[x], 0)
  52. self.draw_bar(x, right[x], self.gui.height / 2)
  53. else:
  54. self.draw_line(x, left[x], 0)
  55. self.draw_line(x, right[x], self.gui.height / 2)
  56. if __name__ == "__main__":
  57. import util
  58. i = util.getInput()
  59. t = util.getTarget(i)
  60. a = AudioVisualizer(t)
  61. util.loop(t, a.draw)