Skip to content

Instantly share code, notes, and snippets.

@Annihil
Created April 16, 2017 17:56
Show Gist options
  • Save Annihil/d6a69355b2f531a66b5c24fb81381540 to your computer and use it in GitHub Desktop.
Save Annihil/d6a69355b2f531a66b5c24fb81381540 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
import lazylights, pyaudio, struct, math, sys
bulbs = lazylights.find_bulbs(expected_bulbs=1)
# lazylights.set_power(bulbs, True)
SHORT_NORMALIZE = (1.0 / 32768.0)
def get_rms(block):
count = len(block) / 2
format = "%dh" % (count)
shorts = struct.unpack(format, block)
# iterate over the block.
sum_squares = 0.0
for sample in shorts:
# sample is a signed short in +/- 32768.
# normalize it to 1.0
n = sample * SHORT_NORMALIZE
sum_squares += n * n
return math.sqrt(sum_squares / count)
CHUNK = 256
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 48000 # [16000.0, 24000.0, 32000.0, 48000.0]
RECORD_SECONDS = 60
REFRESH = RATE / CHUNK / 5
p = pyaudio.PyAudio()
stream = p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
frames_per_buffer = CHUNK,
input_device_index = int(sys.argv[1]))
frames = []
total = 0
# for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
i = 1
hue = 0
while (1):
data = stream.read(CHUNK)
frames.append(data)
amplitude = get_rms(data)
total += amplitude
mean = total / i
brightness = amplitude / mean
if i % REFRESH == 0:
hue += 1
print "\r", i, "{:.5f}".format(mean), "{:.5f}".format(amplitude), "{:.5f}".format(1 / mean), "{:.5f}".format(brightness),
sys.stdout.flush()
lazylights.set_state(bulbs, hue=hue, saturation=1.0, brightness=brightness, kelvin=8000, fade=0025, raw=False)
if hue == 359:
hue = 0;
i += 1
stream.stop_stream()
stream.close()
p.terminate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment