首页 > 解决方案 > 同时使用 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

标签: multithreadingspeech-recognitionpyaudiopython-3.9

解决方案


您可以使用语音识别录制和保存声音。只需使用这部分代码,它就会创建一个 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('')

推荐阅读