-
Notifications
You must be signed in to change notification settings - Fork 0
/
matplotlib_fft.py
executable file
·84 lines (71 loc) · 2.06 KB
/
matplotlib_fft.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
#!/usr/bin/env python
# encoding: utf-8
## Module infomation ###
# Python (3.4.4)
# numpy (1.10.2)
# PyAudio (0.2.9)
# matplotlib (1.5.1)
# All 32bit edition
########################
import numpy as np
import pyaudio
import matplotlib.pyplot as plt
class SpectrumAnalyzer:
FORMAT = pyaudio.paFloat32
CHANNELS = 1
RATE = 8000
CHUNK = 8000
START = 0
N = 512
wave_x = 0
wave_y = 0
spec_x = 0
spec_y = 0
data = []
def __init__(self):
self.pa = pyaudio.PyAudio()
self.stream = self.pa.open(format = self.FORMAT,
channels = self.CHANNELS,
rate = self.RATE,
input = True,
output = False,
frames_per_buffer = self.CHUNK)
# Main loop
self.loop()
def loop(self):
try:
while True :
self.data = self.audioinput()
self.fft()
self.graphplot()
except KeyboardInterrupt:
self.pa.close()
print("End...")
def audioinput(self):
ret = self.stream.read(self.CHUNK)
ret = np.fromstring(ret, np.float32)
return ret
def fft(self):
self.wave_x = range(self.START, self.START + self.N)
self.wave_y = self.data[self.START:self.START + self.N]
self.spec_x = np.fft.fftfreq(self.N, d = 1.0 / self.RATE)
y = np.fft.fft(self.data[self.START:self.START + self.N])
self.spec_y = [np.sqrt(c.real ** 2 + c.imag ** 2) for c in y]
def graphplot(self):
plt.clf()
# wave
plt.subplot(311)
plt.plot(self.wave_x, self.wave_y)
plt.axis([self.START, self.START + self.N, -0.5, 0.5])
plt.xlabel("time [sample]")
plt.ylabel("amplitude")
#Spectrum
plt.subplot(312)
plt.plot(self.spec_x, self.spec_y, marker= 'o', linestyle='-')
plt.axis([0, self.RATE / 2, 0, 50])
plt.xlabel("frequency [Hz]")
plt.ylabel("amplitude spectrum")
#Pause
plt.pause(.001)
if __name__ == "__main__":
spec = SpectrumAnalyzer()