-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasus_soundlighting.py
234 lines (195 loc) · 6.97 KB
/
asus_soundlighting.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# -*- coding: utf-8 -*-
#!/usr/bin/python
"""
Created on Sat Sep 26 11:22:57 2015
@author: William Herrera
Python 2.7 code to analyze sound and use as interface with ASUS G20 lighting
IMPORTANT: run as administrator
Acknowledgements:
This file's code structure owes greatly to the following project:
Juliana Pena's Arduino code at
http://julip.co/2012/05/arduino-python-soundlight-spectrum/
"""
import pyaudio
import numpy
import matplotlib.mlab
import struct
import light_acpi as lacpi
MAX = 0
SEGMENTS = 9
CHUNK_EXPONENT = 15
LIGHT_ROTATION_INTERVAL = 0
DEVICE_NUMBER = 2
def list_devices(do_print=True):
"""
List all audio input devices
"""
paud = pyaudio.PyAudio()
text = "Audio Device Options:\n"
devs = {}
i = 0
ndev = paud.get_device_count()
while i < ndev:
dev = paud.get_device_info_by_index(i)
if dev['maxInputChannels'] > 0:
dev_line = str(i) + '. ' + dev['name']
devs[i] = dev_line
text = text + dev_line + "\n"
i += 1
if do_print:
print text
return ndev, devs
def asus_soundlight(do_print=True):
"""
Get sound samples and adjust LED light color accordingly
"""
# Change chunk if too fast/slow, never less than 2**13
chunk = 2**CHUNK_EXPONENT
samplerate = 44100
# CHANGE THIS TO CORRECT INPUT DEVICE
# Look at recording devices and right click to show hidden devices,
# and enable the mixing device. Enabling stereo mixing in your
# sound card will make your sound output an input.
# Use list_devices() to list all your input devices
# and choose the mixed device as input device below
device = DEVICE_NUMBER
paud = pyaudio.PyAudio()
stream = paud.open(format=pyaudio.paInt16,
channels=2,
rate=samplerate,
input=True,
frames_per_buffer=chunk,
input_device_index=device)
if do_print:
print "Starting, use Ctrl+C to stop"
try:
l_lighting = lacpi.ASUSLighting(lacpi.DPATH, lacpi.LEFT_VERTICAL)
r_lighting = lacpi.ASUSLighting(lacpi.DPATH, lacpi.RIGHT_VERTICAL)
b_lighting = lacpi.ASUSLighting(lacpi.DPATH, lacpi.BASE_HORIZONTAL)
do_rotate_interval = LIGHT_ROTATION_INTERVAL
rotate_state = 0
while True:
try:
data = stream.read(chunk)
except IOError:
pass
# Do FFT
levels = get_cutouts(data, samplerate)
# Make all levels to be <= 255
l_max = max(levels)
for idx in range(0, SEGMENTS):
levels[idx] = int(round(levels[idx] * 255.0 / l_max))
saturate_color(levels)
if do_rotate_interval == 1:
rotate_state += 1
rotate_state %= 3
do_rotate_interval = LIGHT_ROTATION_INTERVAL
if do_rotate_interval > 0:
do_rotate_interval -= 1
rotate_levels(levels, rotate_state)
# set ASUS G20aj lighting colors
b_lighting.set_rgb(levels[0], levels[1], levels[2])
r_lighting.set_rgb(levels[3], levels[4], levels[5])
l_lighting.set_rgb(levels[6], levels[7], levels[8])
except KeyboardInterrupt:
pass
finally:
if do_print:
print "\nStopping"
stream.close()
paud.terminate()
def rotate_levels(seq, rtype):
"""
rotate around light postions colors
"""
if rtype == 1:
saveseq = seq[:3]
seq[:3] = seq[6:]
seq[6:] = seq[3:6]
seq[3:6] = saveseq
elif rtype == 2:
saveseq = seq[:3]
seq[:3] = seq[3:6]
seq[3:6] = seq[6:]
seq[6:] = saveseq
return seq
def sat_trip(cred, cgreen, cblue):
"""
saturate rgb color
"""
mult = 255.0 / (float(max(cred, cgreen, cblue))**4)
return int(mult * float(cred) ** 4), \
int(mult * float(cgreen) ** 4), \
int(mult * float(cblue) ** 4)
def saturate_color(col):
"""
saturate the colrs representing sound levels
"""
if len(col) == 9:
col[0], col[1], col[2] = sat_trip(col[0], col[1], col[2])
col[3], col[4], col[5] = sat_trip(col[3], col[4], col[5])
col[6], col[7], col[8] = sat_trip(col[6], col[7], col[8])
return col
def equalize(levels, within_factor=3.0):
"""
makes levels all within a factor of within of each other
"""
new_levels = []
largest = 0.0
for idx in range(len(levels)):
new_levels.append(numpy.abs(levels[idx]))
if new_levels[idx] < 0.0001:
new_levels[idx] = 0.0001
largest = max(largest, new_levels[idx])
least_allowed = largest / within_factor
loops = 0
for idx in range(len(new_levels)):
while new_levels[idx] < least_allowed and loops < 100:
loops += 1
new_levels[idx] *= 2.0
return new_levels
def get_cutouts(chunkdata, srate, nfft=2048): #pylint: disable-msg=R0914
"""
get a summed amplitude of power spectrum between low_cut and high-cut
normalize this, then get amplitudes of specific frequency ranges
that correspond to 3 intervals each in bass, midrange, and treble:
20 Hz - 80 Hz = Low Bass
80 Hz-160 Hz = Bass
160 Hz - 320 Hz = Hi Bass
320 Hz - 640 Hz = Low Mid Range
640 Hz - 1280 Hz = Mid Mid range
1280 Hz - 2560 Hz = High Midrange
2560 Hz - 5120 Hz = Low Treble
5120 Hz - 10240 Hz = Mid treble
10240 Hz- 20480 Hz = High Treble
"""
# Convert raw sound data to Numpy array
fmt = "%dH"%(len(chunkdata)/2)
unpackdata = struct.unpack(fmt, chunkdata)
np_chunk = numpy.array(unpackdata, dtype='h')
# normalize epoch and then psd
sum_chunk = np_chunk.sum()
if sum_chunk != 0:
norm_chunk = np_chunk / sum_chunk
else:
norm_chunk = np_chunk
pxx, freqs = matplotlib.mlab.psd(norm_chunk, NFFT=nfft, Fs=srate)
# the low and mid bass is contaminated by psd edge artifact, so use
# portions of high bass instead.
lowbass = pxx[numpy.logical_and(freqs <= 200, freqs > 100)]
midbass = pxx[numpy.logical_and(freqs <= 300, freqs > 200)]
higbass = pxx[numpy.logical_and(freqs <= 400, freqs > 300)]
lowmidr = pxx[numpy.logical_and(freqs <= 640, freqs > 400)]
midmidr = pxx[numpy.logical_and(freqs <= 1280, freqs > 640)]
higmidr = pxx[numpy.logical_and(freqs <= 2560, freqs > 1280)]
# tweak to treble bands for better color changes during vocals
lowtreb = pxx[numpy.logical_and(freqs <= 7000, freqs > 2560)]
midtreb = pxx[numpy.logical_and(freqs <= 10240, freqs > 7000)]
higtreb = pxx[numpy.logical_and(freqs <= 20480, freqs > 10240)]
sound_levels = [sum(lowbass), sum(midbass), sum(higbass),
sum(lowmidr), sum(midmidr), sum(higmidr),
sum(lowtreb), sum(midtreb), sum(higtreb)]
return equalize(sound_levels)
if __name__ == '__main__':
list_devices()
asus_soundlight(do_print=True)