python-telemetrix-ambilight/beat_detection.py

49 lines
1.5 KiB
Python
Raw Normal View History

2022-03-29 18:34:26 +00:00
import scipy.signal as signal
import pyaudio
from matplotlib import pyplot as plt
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-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-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
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:
freq_dom = cupy.fft.fft(sample,10000)
freqs = cupy.fft.fftfreq(len(freq_dom))
power_bass = cupy.sum(cupy.abs(freq_dom[0:30]))/cupy.sum(cupy.abs(freq_dom))*power
power_bass = max(0,power_bass-275)
print(power_bass)
idmax = cupy.argmax(cupy.abs(freq_dom))
freqmax = abs(freqs[idmax]*SAMPLE_RATE)
board.neopixel_fill(r=int(min(255,power_bass)),g=0,b=0,auto_show=True)
else:
board.neopixel_clear(auto_show=True)
2022-03-29 18:34:26 +00:00
audioStream.stop_stream()
audioStream.close()
audio.terminate()