Skip to content

Instantly share code, notes, and snippets.

@haveyouwantto
Last active November 29, 2022 02:18
Show Gist options
  • Save haveyouwantto/65defcd7e69516803ae3467667e8c092 to your computer and use it in GitHub Desktop.
Save haveyouwantto/65defcd7e69516803ae3467667e8c092 to your computer and use it in GitHub Desktop.
Raspberry Pi Bluetooth Audio LED (with ws281x)
#!/usr/bin/python3
import colorsys
import subprocess
import traceback
import math
import numpy as np
from rpi_ws281x import Color, PixelStrip
# LED Configuration
LED_COUNT = 60
GPIO_PIN = 18
# LED2_COUNT = 15
# GPIO_PIN2 = 13
LOOP_PERIOD = 4500
HUE_DIVISION = 50 * 60
# Start the audio process
ffmpeg = subprocess.Popen(
'ffmpeg -loglevel warning -f alsa -i bluealsa -f s16le -ac 1 -ar 16000 - -f alsa default',
stdout=subprocess.PIPE,
shell=True)
# LED initialization
strip = PixelStrip(LED_COUNT, GPIO_PIN, 800000, 10, False, 255, 0)
# strip2 = PixelStrip(LED2_COUNT, GPIO_PIN2, 800000, 11, False, 255, 1)
strip.begin()
# strip2.begin()
# Set up variables
ratio = 0
zero = Color(0, 0, 0)
print('init')
try:
while True:
# Get samples
buffer = ffmpeg.stdout.read(160 * 2)
wave = np.abs(np.frombuffer(buffer, dtype=np.int16))
ratio = max((np.max(wave) / 32768)**0.5,
ratio - 0.02) # Normalize to [0,1]
# Get color
colorarr = colorsys.hsv_to_rgb(max(0.9 - ratio, 0), 1, 1)
color = Color(int(colorarr[0] * 255), int(colorarr[1] * 255),
int(colorarr[2] * 255))
# Flip
for j in range(LED_COUNT):
if j < LED_COUNT * ratio:
strip.setPixelColor(j, color)
else:
strip.setPixelColor(j, zero)
strip.show()
except:
traceback.print_exc()
print(ratio, color)
finally:
# Turn off the LED
for i in range(LED_COUNT):
strip.setPixelColor(i, zero)
strip.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment