Python 使用 SpeechRecognition 3.8.1 库无法进行语音识别

Python speech recognition is not working using SpeechRecognition 3.8.1 library

在我的 Python 3.8.6 项目中,我为我的 windows 10 计算机安装了“pip install SpeechRecognition”。代码示例如下,

    import speech_recognition as sr
    
    listener = sr.Recognizer()
    try:
        with sr.Microphone() as source:
            print('Listening...')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            print(command)
    except:
        print("Something else went wrong")
        pass

在运行这段代码之后,输出如下,

Something else went wrong

我已经在我的笔记本电脑上内置了麦克风,而且我还使用外接 USB 麦克风对其进行了检查。那么这里的问题是什么?是否需要任何硬件配置来解决这个问题?

在PyPI 的Speech Recognition Readme 中,您可以看到有一个PyAudio Section。这意味着你必须在你的机器上安装 PyAudio。但是如果你安装了PyAudio却报错了,你需要把报错不加try except blocks分享出来,以便我们分析报错并给出解决方案。

要安装 PyAudio,请在终端中执行 pip install pyaudio

有时 pip install pyaudio 会抛出类似这样的错误:

Collecting PyAudio
  Using cached https://files.pythonhosted.org/packages/ab/42/b4f04721c5c5bfc196ce156b3c768998ef8c0ae3654ed29ea5020c749a6b/PyAudio-0.2.11.tar.gz
Installing collected packages: PyAudio
  Running setup.py install for PyAudio ... error
    Complete output from command C:\Users\username\AppData\Local\Programs\Python\Python37-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\Users\username\AppData\Local\Temp\pip-install-e5le61j0\PyAudio\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\username\AppData\Local\Temp\pip-record-adj3zivl\install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build\lib.win32-3.7
    copying src\pyaudio.py -> build\lib.win32-3.7
    running build_ext
    building '_portaudio' extension
    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

    ----------------------------------------
Command "C:\Users\username\AppData\Local\Programs\Python\Python37-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\Users\username\AppData\Local\Temp\pip-install-e5le61j0\PyAudio\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\username\AppData\Local\Temp\pip-record-adj3zivl\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\username\AppData\Local\Temp\pip-install-e5le61j0\PyAudio\

修复此错误的步骤:

  • 转到您的终端并执行 python --version,对于 Optimus Prime,他的版本是 Python 3.8.6
  • 查看您的 Python 安装是 64 位还是 32 位,您可以前往 Python 终端
  • 查看
  • 根据您的 Python 版本和 Python 安装(64 位/32 位)下载 PyAudio Wheel file
  • 在下载 Wheel 文件 (.whl) 的目录中打开一个终端
  • 然后执行pip install <name of your wheel file>

大功告成!