Skip to content

Beatmatch

David Konsumer edited this page Sep 6, 2017 · 1 revision

Kyle Dixon made an awesome python script to control a bunch of lights to a beat:

Video of light synced to sound

here is the source:

#!/usr/bin/python

## Kyle Dixon - TP-Link Beat Match
## Change the variables below for a more customized experience. Code is written for one color(130) and one white(120) bulb. 

from __future__ import division
from random import randint
import os
import alsaaudio, time, audioop
random = randint(1, 360)

######################### SETTINGS ###########################
changefreq = 1 # Color Change frequency. Use "random for random quickly"
blackness = 0 # amount of time lights are off (1-50 is a good range) Higher = More Blackness
sample = 10 # sample length of music to get levels from (5 gives very good latency, 10 gives better accuracy)
######################## END SETTINGS ########################

hue = 1
average = 50
count = 0
sum = 0
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)

inp.setchannels(1)
inp.setrate(8000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(160) # fps
max = 0
min = 100000
while True:
    l,data = inp.read()
    if l:
	count = count + 1;
	slevstring = audioop.max(data, 2)
	slevint = int(slevstring)
	if slevint > max:
		max = max + slevint
	if slevint < min:
		min = 0 + slevint 
	if count > sample:
		count = 0
		max = 0
		min = 100000
	
	if slevint > min + blackness:
		diff = max - min # difference between minimum and max level for the last x frames
		abvmin = slevint - min # current level above minimum
		l = abvmin / diff * 100 # get the percentage of loudness compared to the last x frames
		lv = int(l)
		white = lv - 15
		if white < 1:
			white = 1
		random = randint(1, 360)
		os.system('tplight hsb 192.168.86.153 100 100 ' + str(white) + ' &'); #Enter your white bulb's IP
		os.system('tplight hsb 192.168.86.154 ' + str(hue) + ' 100 ' + str(lv) + ' &'); #Enter your color bulb's IP
## Uncomment below and comment random to alternate between random color and fade
#		hue = hue + changefreq;
		hue = random
		if hue > 360:
			hue = 1;
	else:
		os.system('tplight off 192.168.86.154 &'); #Enter your white bulb's IP
	        os.system('tplight off 192.168.86.153 &'); #Enter your color bulb's IP
Clone this wiki locally