def record(threshold=THRESHOLD, silence=SILENCE_LIMIT):
"""
Listens to Microphone, records voice until phrase ends.
A "phrase" is sound surrounded by silence (according to threshold).
:param int threshold: Intensity value that defines silence.
lower than threshold is silence.
:param silence: Max ammount of seconds where only silence is
recorded. When this time passes the recording finishes.
"""
# Open stream
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print ("* Listening mic. ")
frames = []
cur_data = ''
rel = RATE/CHUNK
window = deque(maxlen=silence * rel)
prev_audio = deque(maxlen=PREV_AUDIO * rel)
start = False
exit_loop = 0
while (exit_loop != 1):
cur_data = stream.read(CHUNK)
window.append(math.sqrt(abs(audioop.avg(cur_data, 4))))
if(sum([x > THRESHOLD for x in window]) > 0):
if(not start):
print ("recording..")
start = True
frames.append(cur_data)
elif start is True:
print ("Finished")
save_audio(list(prev_audio) + frames, p)
start = False
window = deque(maxlen=silence * rel)
prev_audio = deque(maxlen=0.5 * rel)
frames = []
exit_loop = 1
else:
prev_audio.append(cur_data)
print ("Done recording")
stream.close()
p.terminate()
评论列表
文章目录