同时使用pyaudio和语音识别

Using pyaudio and Speech Recognition at the same time

我想在使用语音识别时录制音频并获取音频文件。出于某种原因,我的程序总是在几分钟后崩溃。它也不会创建音频文件。 我怀疑使用线程存在问题,因为这两个进程都可以自己正常工作。不幸的是我找不到任何东西。 有谁知道我如何解决这个问题或如何在录制声音时使用语音识别?

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('')