python-telemetrix-ambilight/beat_detection_rainbow_gpu.py

64 lines
2.0 KiB
Python
Raw Permalink Normal View History

2022-03-29 18:34:26 +00:00
import scipy.signal as signal
import pyaudio
2022-03-30 17:43:46 +00:00
from matplotlib import pyplot
2022-03-29 18:34:26 +00:00
import numpy as np
2022-03-30 13:15:41 +00:00
from time import sleep, time
import cupy
import atexit
import signal
from telemetrix_rpi_pico import telemetrix_rpi_pico
2022-03-30 17:43:46 +00:00
import colorsys
2022-03-29 18:34:26 +00:00
2022-03-30 13:15:41 +00:00
def sigint_handler(signal=None, frame=None):
print ('KeyboardInterrupt is caught')
board.neopixel_clear()
sleep(0.75)
board.shutdown()
exit()
signal.signal(signal.SIGINT, sigint_handler)
atexit.register(sigint_handler)
NUM_LEDS = 60
board = telemetrix_rpi_pico.TelemetrixRpiPico()
board.set_pin_mode_neopixel(pin_number=2,num_pixels=NUM_LEDS)
board.neopixel_clear(auto_show=True)
SAMPLE_SIZE = 4096
SAMPLE_RATE = 48000
2022-03-30 17:43:46 +00:00
LOWPASS_CUTOFF = 50
AMPLITUDE_MULTIPLIER = 0.1
VELOCITY = 6
2022-03-29 18:34:26 +00:00
audio = pyaudio.PyAudio()
2022-03-30 13:15:41 +00:00
audioStream = audio.open(format=pyaudio.paInt16, channels=1, rate=SAMPLE_RATE, input=True, frames_per_buffer=SAMPLE_SIZE)
2022-03-29 18:34:26 +00:00
2022-03-30 17:43:46 +00:00
pastBassSignal = [0]*100
timecounter = 0
2022-03-29 18:34:26 +00:00
while True:
data = audioStream.read(SAMPLE_SIZE)
2022-03-30 13:15:41 +00:00
sample = cupy.frombuffer(data, dtype=np.int16)
power = cupy.sum(cupy.abs(sample))/SAMPLE_SIZE
if power > 1000:
2022-03-30 17:43:46 +00:00
freq_dom = cupy.fft.rfft(sample,10000)
freqs = cupy.fft.rfftfreq(len(freq_dom))
power_bass = cupy.sum(cupy.abs(freq_dom[0:LOWPASS_CUTOFF]))/cupy.sum(cupy.abs(freq_dom))*power
power_bass = max(0,power_bass-250)
if len(pastBassSignal)>100:
pastBassSignal.pop(0)
pastBassSignal.append(power_bass)
2022-03-30 13:15:41 +00:00
print(power_bass)
2022-03-30 17:43:46 +00:00
2022-03-30 13:15:41 +00:00
idmax = cupy.argmax(cupy.abs(freq_dom))
freqmax = abs(freqs[idmax]*SAMPLE_RATE)
2022-03-30 17:43:46 +00:00
brightness = int(min(255,power_bass*AMPLITUDE_MULTIPLIER))
for j in range(0,NUM_LEDS):
r, g, b = colorsys.hsv_to_rgb(((-timecounter*VELOCITY+j*4)%360)/360,1,1)
board.neo_pixel_set_value(j,r=int(r*brightness),g=int(g*brightness),b=int(b*brightness))
timecounter+=1
board.neopixel_show()
2022-03-30 13:15:41 +00:00
else:
board.neopixel_clear(auto_show=True)
2022-03-29 18:34:26 +00:00
audioStream.stop_stream()
audioStream.close()
audio.terminate()