-
Notifications
You must be signed in to change notification settings - Fork 1
/
dsp.py
106 lines (87 loc) · 2.73 KB
/
dsp.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
import numpy as np
import echonest.audio as audio
CHUNK=256
WINDOW = np.blackman(CHUNK)
class DSP:
def __init__(self,audioFile,chunk):
self.signal=monoSignal(audioFile,chunk)
# todo - compute spectrum
self.chunk=chunk
self.calcSpectrum()
self._centroid=None
self._spread=None
def calcSpectrum(self):
nZeros = CHUNK - self.signal.size % CHUNK
padded = np.hstack([self.signal, np.zeros(nZeros)])
# frames are rows
reshaped = padded.reshape(padded.size/CHUNK,CHUNK)
# apply window to each frame
reshaped = np.apply_along_axis(lambda x: x*WINDOW, 1, reshaped)
# do fft on each row
S = np.fft.rfft(reshaped)
# get power spectrum
SPow = abs(S)**2
# calc mean for each bucket - 0 is column axis
self.spec = SPow.mean(0)
# remove DC offset
self.spec[0]==0
def spread(self):
if self._spread:
return self._spread
else:
sum = self.spec.sum()
self._spread = 0
centroid = self.centroid()
for i in range(0,len(self.spec)):
x=self.spec[i]
p=x/sum
self._spread += (x-centroid)**2*p
return self._spread
def centroid(self):
if self._centroid:
return self._centroid
else:
a=0
for i in range(0,len(self.spec)):
a=i*self.spec[i]
self._centroid = a/self.spec.sum()
return self._centroid
def kurtosis(self):
sum = self.spec.sum()
moment = 0
centroid = self.centroid()
for i in range(0,len(self.spec)):
x=self.spec[i]
p=x/sum
moment+=(x-centroid)**4*p
return moment/(self.spread()**2)
def peak(self):
return self.signal.max
def energy(self):
return self.spec.sum()
def halfIndex(self):
return int(len(self.spec)/2.0)
def hf(self):
i=int(len(self.spec)*(2/3.0))
hfc=self.hfc()
return np.sum(hfc[-i:])/i
def lf(self):
i=int(len(self.spec)*(1/3.0))
return np.sum(self.spec[:i])/i
def hfc(self,a=1):
l=len(self.spec)
return self.spec*np.linspace(0,l-1,l)**a
def apply(self):
# todo: apply all analyses on chunk
self.chunk.peak = self.peak()
self.chunk.hf = self.hf()
self.chunk.lf = self.lf()
self.chunk.energy = self.energy()
self.chunk.kurtosis = self.kurtosis()
return self.chunk
def monoSignal(audioFile,chunk):
audioChunk = audio.getpieces(audioFile,[chunk])
arr = audioChunk.data
if arr.ndim==2:
return arr.mean(1)
return arr