首页 > 解决方案 > 使用 Python 和 PyAudio 的语音转文本无法在操作系统上运行

问题描述

我正在尝试在 Python 3.7(OS X/内置麦克风)上使用语音识别库

这是我到目前为止使用的代码:

import speech_recognition as sr

r = sr.Recognizer()
with sr.Microphone() as source:
    print("Say something!")
    audio = r.listen(source)

print("Google Speech Recognition thinks you said " + r.recognize_google(audio))

但是,当我运行程序时,没有输出,也没有错误消息。但是当我点击“停止”按钮时,会出现此错误消息

回溯(最近一次通话最后):文件“/Users/diandraelmira/PycharmProjects/untitled/venv/APP.py”,第 6 行,音频 = r.listen(source) 文件“/Users/diandraelmira/PycharmProjects/untitled/venv /lib/python3.7/site-packages/speech_recognition/init .py”,第 620 行,在监听缓冲区 = source.stream.read (source.CHUNK) 文件“/Users/diandraelmira/PycharmProjects/untitled/venv/lib/ python3.7/site-packages/speech_recognition/ init .py”,第 161 行,在读取返回 self.pyaudio_stream.read(size, exception_on_overflow=False) 文件“/Users/diandraelmira/PycharmProjects/untitled/venv/lib/python3. 7/site-packages/pyaudio.py”,第 608 行,在读取中返回 pa.read_stream(self._stream, num_frames, exception_on_overflow) KeyboardInterrupt

我怎样才能解决这个问题?

标签: pythonpython-3.xspeech-recognitionspeech-to-textpyaudio

解决方案


使用以下代码:

#import library

import speech_recognition as sr

# Initialize recognizer class (for recognizing the speech)

r = sr.Recognizer()

# Reading Microphone as source
# listening the speech and store in audio_text variable

with sr.Microphone() as source:
    print("Talk")
    audio_text = r.listen(source)
    print("Time over, thanks")
# recoginize_() method will throw a request error if the API is unreachable, hence using exception handling
    
    try:
        # using google speech recognition
        print("Text: "+r.recognize_google(audio_text))
    except:
         print("Sorry, I did not get that")

希望它有效。


推荐阅读