-
Notifications
You must be signed in to change notification settings - Fork 1
/
mic.py
44 lines (39 loc) · 1.26 KB
/
mic.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
import wave
import pyaudio
def record_mic(output_file="record.wav", time=0):
_chunk = 1024
_format = pyaudio.paInt16
_channels = 2
_rate = 44100
audio = pyaudio.PyAudio()
stream = audio.open(format=_format,
channels=_channels,
rate=_rate,
input=True,
frames_per_buffer=_chunk)
frames = []
if time is not 0:
for i in range(0, int(_rate * time * 0.001 / _chunk)):
data = stream.read(_chunk, exception_on_overflow=False)
frames.append(data)
else:
import os, sys, select
while True:
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
try:
line = input()
except:
line = raw_input()
break
data = stream.read(_chunk, exception_on_overflow=False)
frames.append(data)
stream.stop_stream()
stream.close()
audio.terminate()
out_file = wave.open(output_file, 'wb')
out_file.setnchannels(_channels)
out_file.setsampwidth(audio.get_sample_size(_format))
out_file.setframerate(_rate)
out_file.writeframes(b''.join(frames))
out_file.close()
return 0