multithreading - 同时使用 pyaudio 和语音识别
问题描述
我想在使用语音识别时录制音频并获取音频文件。出于某种原因,我的程序总是在几分钟后崩溃。它也不会创建音频文件。我怀疑使用线程存在问题,因为两个进程本身都可以正常工作。不幸的是,我找不到任何东西。有谁知道如何解决此问题或如何在录制声音时使用语音识别?
import threading
import speech_recognition as sr
import pyaudio
import wave
import time
status = True
def record():
chunk = 1024
sample_format = pyaudio.paInt16
channels = 1
fs = 44100
filename = 'output.wav'
global status
p = pyaudio.PyAudio()
print('Recording')
stream = p.open(format=sample_format,
channels=channels,
rate=fs,
frames_per_buffer=chunk,
input=True)
frames = []
while status == True:
data = stream.read(chunk)
frames.append(data)
stream.stop_stream()
stream.close()
p.terminate()
print('Finished recording')
wf = wave.open(filename, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(sample_format))
wf.setframerate(fs)
wf.writeframes(b''.join(frames))
wf.close()
def get_audio():
while True:
r = sr.Recognizer()
with sr.Microphone() as source:
print("Höre zu ...")
audio = r.listen(source)
said = ''
try:
said = r.recognize_google(audio, language="de_DE")
print(said)
except Exception as e:
print('')
thread1=threading.Thread(target=record)
thread1.start()
thread2=threading.Thread(target=get_audio)
thread2.start()
time.sleep(5)
status=False
解决方案
您可以使用语音识别录制和保存声音。只需使用这部分代码,它就会创建一个 Speech.wav 文件:
def get_audio():
while True:
r = sr.Recognizer()
with sr.Microphone() as source:
print("Höre zu ...")
audio = r.listen(source)
with open('speech.wav', 'wb') as f:
f.write(audio.get_wav_data())
try:
said = r.recognize_google(audio, language="de_DE")
print(said)
except Exception as e:
print('')
推荐阅读
- python - pymongo 在可能包含重复项的 mongo 数据库中插入许多文档
- android - 如何使用处理程序将消息从一个线程发送到fargment线程
- python - 如何在 Android 上将 Pytesseract 用于 Kivy 应用程序?
- javascript - JavaScript 回调函数中的 if else 语句故障
- sql - 用于获取单个日期的所有日期/时间的 SQL
- python-3.x - 未找到 Python3 / pip3 模块
- r - 在使用非标准评估的函数中,检查列是否存在
- javascript - 通过javascript将数组转换为json对象
- .net-core - .Net Core 3.1 中的 Couchbase 通用存储库
- macros - 同名的 Common Lisp 局部阴影函数