forked from atuldo/real-time-plot-microphone-kivy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
64 lines (52 loc) · 1.64 KB
/
main.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
"""Real time plotting of Microphone level using kivy
"""
from kivy.lang import Builder
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.garden.graph import MeshLinePlot
from kivy.clock import Clock
from threading import Thread
import audioop
import pyaudio
def get_microphone_level():
"""
source: http://stackoverflow.com/questions/26478315/getting-volume-levels-from-pyaudio-for-use-in-arduino
audioop.max alternative to audioop.rms
"""
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
p = pyaudio.PyAudio()
s = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=chunk)
global levels
while True:
data = s.read(chunk)
mx = audioop.rms(data, 2)
if len(levels) >= 100:
levels = []
levels.append(mx)
class Logic(BoxLayout):
def __init__(self,):
super(Logic, self).__init__()
self.plot = MeshLinePlot(color=[1, 0, 0, 1])
def start(self):
self.ids.graph.add_plot(self.plot)
Clock.schedule_interval(self.get_value, 0.001)
def stop(self):
Clock.unschedule(self.get_value)
def get_value(self, dt):
self.plot.points = [(i, j/5) for i, j in enumerate(levels)]
class RealTimeMicrophone(App):
def build(self):
return Builder.load_file("look.kv")
if __name__ == "__main__":
levels = [] # store levels of microphone
get_level_thread = Thread(target = get_microphone_level)
get_level_thread.daemon = True
get_level_thread.start()
RealTimeMicrophone().run()