AttributeError: Could not find PyAudio; check installation...can't use speech Recognition

AttributeError: Could not find PyAudio; check installation...can't use speech Recognition

我正在尝试制作一个基本的语音识别助手。当我 运行 代码时,它告诉我:

Traceback (most recent call last):
  File "C:\Users\Mo.haytham\AppData\Local\Programs\Python\Python37\lib\site-packages\speech_recognition\__init__.py", line 108, in get_pyaudio
    import pyaudio
ModuleNotFoundError: No module named 'pyaudio'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/Mo.haytham/.PyCharmCE2018.3/config/scratches/ALPHA_BASIC.py", line 22, in <module>
    hear()
  File "C:/Users/Mo.haytham/.PyCharmCE2018.3/config/scratches/ALPHA_BASIC.py", line 13, in hear
    with sr.Microphone() as sourse:
  File "C:\Users\Mo.haytham\AppData\Local\Programs\Python\Python37\lib\site-packages\speech_recognition\__init__.py", line 79, in __init__
    self.pyaudio_module = self.get_pyaudio()
  File "C:\Users\Mo.haytham\AppData\Local\Programs\Python\Python37\lib\site-packages\speech_recognition\__init__.py", line 110, in get_pyaudio
    raise AttributeError("Could not find PyAudio; check installation")
AttributeError: Could not find PyAudio; check installation 

我尝试 pip install pyaudio 但随后出现此错误:

Running setup.py clean for pyaudio
Failed to build pyaudio
Installing collected packages: pyaudio
  Running setup.py install for pyaudio ... error
    ERROR: Complete output from command 'c:\users\mo.haytham\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\Users\MO2D8C~1.HAY\AppData\Local\Temp\pip-install-o2
10x3zl\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\MO2
D8C~1.HAY\AppData\Local\Temp\pip-record-hr7kket1\install-record.txt' --single-version-externally-managed --compile:
    ERROR: running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.7
    copying src\pyaudio.py -> build\lib.win-amd64-3.7
    running build_ext
    building '_portaudio' extension
    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/
    ----------------------------------------
ERROR: Command "'c:\users\mo.haytham\appdata\local\programs\python\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\Users\MO2D8C~1.HAY\AppData\Local\Temp\pip-install-o210x3zl\pyaudio\setup.p
y'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\MO2D8C~1.HAY\AppData\Local\
Temp\pip-record-hr7kket1\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\MO2D8C~1.HAY\AppData\Local\Temp\pip-install-o210x3zl\pyaudio\
def hear():
    import speech_recognition as sr
    ear = sr.Recognizer()
    with sr.Microphone() as sourse:
        print("listening...")
        audio = ear.listen(sourse)
        try:
            text = ear.recognize_google(audio)
            print(text)
        except:
            print("i didn't get that...")

hear()

您似乎缺少构建 pyaudio 所需的一些文件。

根据您的错误日志,

Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build >Tools": https://visualstudio.microsoft.com/downloads/

您需要安装 Microsoft Visual C++ Build Tools

我还发现 PyAudio 安装可能会很痛苦,对于某些最终用户来说甚至是交易破坏者,因为安装困难。原则上,speech_recognition.Recognizer.listen() 没有理由不能从 sounddevice or soundcard or audiomath 等其他音频库获取输入,所有这些通常都更容易安装。幸运的是,虽然 speech_recognition 代码本身只提供 PyAudio 实现,但在内部它只需要 Microphone 的几个属性是鸭子类型的,以允许它 listen() 成功。具体来说:

  • source 必须是 speech_recognition.AudioSource 子类的实例
  • source.stream 必须是非 None 而源处于活动状态
  • source.CHUNK 必须是每个块的(整数)样本数
  • source.SAMPLE_RATE必须是采样率
  • source.SAMPLE_WIDTH必须是每个样本的字节数
  • source.stream.read(numberOfSamples)必须return原始单声道音频数据

这是一个使用 audiomath 的鸭式解决方案:

import audiomath; audiomath.RequireAudiomathVersion( '1.12.0' )
import speech_recognition  # NB: python -m pip install SpeechRecognition

class DuckTypedMicrophone( speech_recognition.AudioSource ): # descent from AudioSource is required purely to pass an assertion in Recognizer.listen()
    def __init__( self, device=None, chunkSeconds=1024/44100.0 ):  # 1024 samples at 44100 Hz is about 23 ms
        self.recorder = None
        self.device = device
        self.chunkSeconds = chunkSeconds
    def __enter__( self ):
        self.nSamplesRead = 0
        self.recorder = audiomath.Recorder( audiomath.Sound( 5, nChannels=1 ), loop=True, device=self.device )
        # Attributes required by Recognizer.listen():
        self.CHUNK = audiomath.SecondsToSamples( self.chunkSeconds, self.recorder.fs, int )
        self.SAMPLE_RATE = int( self.recorder.fs )
        self.SAMPLE_WIDTH = self.recorder.sound.nbytes
        return self
    def __exit__( self, *blx ):
        self.recorder.Stop()
        self.recorder = None
    def read( self, nSamples ):
        sampleArray = self.recorder.ReadSamples( self.nSamplesRead, nSamples )
        self.nSamplesRead += nSamples
        return self.recorder.sound.dat2str( sampleArray )
    @property
    def stream( self ): # attribute must be present to pass an assertion in Recognizer.listen(), and its value must have a .read() method
        return self if self.recorder else None

if __name__ == '__main__':
    import speech_recognition as sr
    r = sr.Recognizer()
    with DuckTypedMicrophone() as source:
        print('\nSay something to the %s...' % source.__class__.__name__)
        audio = r.listen(source)
    print('Got it.')
    print('\nUnderstood: "%s"\n' % r.recognize_google(audio))

    if 0: # plot and/or play back captured audio
        s = audiomath.Sound(audio.get_wav_data(), fs=audio.sample_rate, nChannels=1)
        s.Play()
        s.Plot()

终端类型

pip install pipwin

然后

pipwin install pyaudio

如果您是 ubuntu 18.04 用户,请按照以下步骤操作

sudo apt-get install portaudio19-dev python-pyaudio

然后

pip install PyAudio

sudo apt-get install libportaudio-dev(先试试这个) sudo apt-get install portaudio19-dev(而不是使用这个) 稍后安装 pyaudio (python -m pip install PyAudio)

您在安装 pyaudio 时遇到错误,因为您没有安装 pyaudio 的 c++ 构建工具。

要安装 Mircosoft Visual C++ 14.0,请考虑这个 link

那么, 安装 pyaudio。

如果你在 anaconda 提示符下使用 jupyter notebook 那么

conda install pyaudio

如果你使用 cmd 使用 jupyter notebook,那么在 jupyter cell 上,

import sys
!{sys.executable} -m pip install pyaudio

如果你在 cmd 上 运行 python 文件,

pip3 install pyaudio #for python3

对于您所说的下载 C++ 构建工具的错误,我遇到了同样的错误。我下载了 Microsoft visual studio 运行时,但没有用。然后我下载了 pycharm 带有 anaconda 插件的社区版。我下载了 anaconda,激活了它,然后用 conda 的 python.exe 配置了一个 conda 解释器。然后我输入以下内容: conda 安装 PyAudio 它为我安装了一切。我建议这样做。

PyAudio 在 Python 2.7、3.4、3.5 和 3.6(32 位和 64 位)中受支持。您可能必须安装以上任何一项 python 才能使 PyAudio 正常工作。

即使在安装 pipwin 之后我也遇到了问题,所以我发现在安装 PyAudio 之前执行下面的解决方案

!apt install libasound2-dev portaudio19-dev libportaudio2 libportaudiocpp0 ffmpeg

如果您是 macOS 用户

安装端口

brew install portaudio

然后安装pyaudio

pip install pyaudio