树莓派使用python录音,停止说话时结束
树莓派使用python录音,停止说话时结束
主要是根据麦克检测到声音的大小来判断是否说话完毕
主要逻辑:检测到声音小于某个值后,再停顿一点时间,再次检测,若声音依旧小于某个值,再次检测,若依然小于某个值,则判断为说话结束;如果其中声音再次大于某个值,则重新检测。
代码 listen
// python;
def listen():
temp = 20 #temp为检测声音值
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
RECORD_SECONDS = 2
WAVE_OUTPUT_FILENAME = '/home/pi/Public/test.wav'
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)*[HTML]
#snowboydecoder.play_audio_file()
print("录音开始")
frames = []
stat = True #一重判断
stat2 = False #二重判断
stat3 = False #三重判断
tempnum = 0 #tempnum、tempnum2、tempnum3为时间
tempnum2 = 0
tempnum3 = 0
while stat:
data = stream.read(CHUNK,exception_on_overflow = False)
frames.append(data)
audio_data = np.frombuffer(data, dtype=np.short)
temp = np.max(audio_data)
if(tempnum>30):
if(temp < 1000 and stat2==False):
stat2 = True
tempnum2 = tempnum
print("xxxxxxxxxxxxxxxxx")
if(tempnum > tempnum2 + 5):
print("yyyyyyyyyyyyyyyyy")
if(stat2 and temp < 1000):
stat3 = True
else:
tempnum3 = tempnum
print("zzzzzzzzzzzz")
stat2 = False
if (tempnum > tempnum3 + 5):
print("sssssssssssss")
if (stat2 and stat3 and temp < 1000):
stat = False
else:
tempnum3 = tempnum
print("zzzzzzzzzzzz")
stat3 = False
print(str(temp) + " " + str(tempnum))
tempnum = tempnum + 1
if tempnum > 150: #超时直接退出
stat = False
print("录音结束")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
作为第一篇博客,可能各方面都写得不够好,希望后面继续努力。