首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >同时使用pyaudio和语音识别

同时使用pyaudio和语音识别
EN

Stack Overflow用户
提问于 2021-01-12 23:49:47
回答 1查看 279关注 0票数 0

我想在使用语音识别时录制音频并获取音频文件。由于某些原因,我的程序总是在片刻之后崩溃。它也没有涉及到创建音频文件。我怀疑使用线程会有问题,因为这两个进程各自都工作得很好。不幸的是,我什么也找不到。有没有人知道如何解决这个问题,或者如何在录音时使用语音识别?

代码语言:javascript
运行
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-13 04:22:29

您可以使用语音识别录制和保存声音。只需使用这部分代码,它将创建一个speech.wav文件:

代码语言:javascript
运行
复制
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('')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65687303

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档