Created
January 3, 2015 15:32
-
-
Save hdurdle/a4e3d6745177708e53e7 to your computer and use it in GitHub Desktop.
soundlight (Python to Arduino)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import alsaaudio, wave | |
import numpy | |
import serial | |
import time | |
import struct | |
MAX = 0 | |
def arduino_soundlight(): | |
chunk = 2**9 # Change if too fast/slow, I've tried 2**9 through 2**11 | |
scale = 50 # Change if too dim/bright | |
exponent = 5 # Change if too little/too much difference between loud and quiet | |
samplerate = 44100 | |
port = serial.Serial("/dev/ttyACM0", baudrate=57600, timeout=1.0) | |
time.sleep(2) | |
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE) | |
inp.setchannels(1) | |
inp.setrate(samplerate) | |
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) | |
inp.setperiodsize(1024) | |
while True: | |
l, data = inp.read() | |
try: | |
levels = calculate_levels(data, chunk, samplerate) | |
# Make it look better and send to serial | |
print levels | |
port.write(bytearray([4])) | |
for level in levels: | |
level = max(min(level / scale, 1.0), 0.0) | |
level = level**exponent | |
level = int(level * 255) | |
port.write(bytearray([level])) | |
port.write(bytearray([10])) | |
except Exception: | |
pass | |
def calculate_levels(data, chunk, samplerate): | |
# Use FFT to calculate volume for each frequency | |
global MAX | |
# Convert raw sound data to Numpy array | |
fmt = "%dH"%(len(data)/2) | |
data2 = struct.unpack(fmt, data) | |
data2 = numpy.array(data2, dtype='h') | |
#data2 = numpy.fromstring(data, dtype='int16') | |
# Apply FFT | |
fourier = numpy.fft.fft(data2) | |
ffty = numpy.abs(fourier[0:len(fourier)/2])/1000 | |
ffty1=ffty[:len(ffty)/2] | |
ffty2=ffty[len(ffty)/2::]+2 | |
ffty2=ffty2[::-1] | |
ffty=ffty1+ffty2 | |
ffty=numpy.log(ffty)-2 | |
fourier = list(ffty)[4:-4] | |
fourier = fourier[:len(fourier)/2] | |
size = len(fourier) | |
# Add up for 3 lights | |
levels = [sum(fourier[i:(i+size/3)]) for i in xrange(0, size, size/3)][:3] | |
return levels | |
if __name__ == '__main__': | |
arduino_soundlight() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment