-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsupport_fxns.py
56 lines (49 loc) · 2.01 KB
/
support_fxns.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
# Support functions for data manipulations
import numpy as np
from struct import unpack
# Define constants
tot_frequency = 20000
# The following functions are for the audio spectrum waveform visualisation
def piff(frequency, chunk):
"""
Power Index For Frequency:
power is an array used below in fxn calculate_levels.
It contains the values corresponding to the relative
amplitude of the audio at certain frequencies.
Assuming stream / microphone records from
0 - 20000 Hz, this function returns the index of array power
corresponding to a certain frequency, with results
spread out between the 0th index and the last index of power.
"""
ratio = float(frequency) / tot_frequency
num_indices = chunk/2
index = ratio*num_indices
return int(index)
def calculate_levels(zero_matrix, data, chunk, sample_rate):
weighting = [ 1, 5, 7, 6, 8, 8, 13, 22,
33, 71, 112, 128, 141, 161, 172, 192,
213, 230, 238, 256, 270, 279, 285, 293,
299, 304, 308, 312, 315, 317, 318, 319]
matrix = zero_matrix
# Convert raw data (ASCII string) to numpy array of length chunk/2 +1
data = unpack("%dH"%(len(data)/2),data)
data = np.array(data, dtype='h')
# Apply FFT - real data
fourier=np.fft.rfft(data)
# Remove last element in array to make it the same size as chunk/2
fourier=np.delete(fourier,len(fourier)-1)
# Find average 'amplitude' for specific frequency ranges in Hz
power = np.abs(fourier)
length = len(matrix)
freq_step = tot_frequency/length
for iii in range(length):
freq1 = iii * freq_step
freq2 = (iii + 1) * freq_step
ind1 = piff(freq1, chunk)
ind2 = piff(freq2, chunk)
matrix[iii] = int(np.mean(power[ind1: ind2]))
# Tidy up column values for the LED matrix
matrix = np.divide(np.multiply(matrix, weighting), 16878)
# Set floor at 0 and ceiling at 32 for LED matrix
matrix = matrix.clip(0,32)
return matrix