属性错误:找不到PyAudio;请检查安装...无法使用语音识别。

21
我想制作一个基本的语音识别助手。当我运行代码时,它告诉我:
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()
12个回答

42
在终端中输入。
pip install pipwin

那么

pipwin install pyaudio

1
这将在 Python 3.8.5 中运行,我试图在最新版本中安装它,但不起作用。 - Saad Abbasi

9

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

sudo apt-get install portaudio19-dev python-pyaudio

那么

pip install PyAudio

尝试在Ubuntu 22.04上使用命令sudo apt-get install portaudio19-dev python3-pyaudio - undefined

5

我也发现安装PyAudio可能会让一些终端用户很苦恼,甚至成为无法接受的问题,因为安装有困难。理论上,speech_recognition.Recognizer.listen() 可以从其他音频库(如sounddevice、soundcard或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) 必须返回原始单声道音频数据

这里是使用 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()

4

由于没有C++构建工具来安装pyaudio,您会遇到安装pyaudio的错误。

要安装Microsoft Visual C++ 14.0,请考虑使用此链接:https://dev59.com/uF0a5IYBdhLWcg3w48BP#49986365

然后,安装pyaudio。

如果您在Anaconda提示符上使用jupyter笔记本,则:

conda install pyaudio

如果您正在使用CMD使用Jupyter笔记本电脑,则在Jupyter单元格上,
import sys
!{sys.executable} -m pip install pyaudio

如果你正在cmd上运行Python文件,则:

pip3 install pyaudio #for python3

2

在 Mac M1 上安装 PyAudio 和 PortAudio 的步骤

python3 -m pip install --upgrade pip setuptools wheel
brew install portaudio --HEAD
python3 -m pip install pyaudio --global-option="build_ext" --global-option="-I/opt/homebrew/include" --global-option="-L/opt/homebrew/lib"

1

看起来你缺少一些构建pyaudio所需的文件。

从你的错误日志中可以看出,

需要 Microsoft Visual C++ 14.0。请使用“Microsoft Visual C++ Build >Tools”获取它:https://visualstudio.microsoft.com/downloads/

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


1

即使安装了pipwin,我仍然遇到问题,所以在安装PyAudio之前,请执行以下操作以找到解决方案

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

0

适用于MacOS:

使用以下命令安装portaudio:

brew install portaudio

然后使用以下命令安装pyaudio:

pip install pyaudio


1
你的回答可以通过提供更多支持性信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的回答是否正确。你可以在帮助中心找到关于如何撰写好回答的更多信息。 - undefined

0

sudo apt-get install libportaudio-dev(首先尝试使用此命令) sudo apt-get install portaudio19-dev(如果不行,请使用此命令) 然后安装pyaudio(python -m pip install PyAudio)


0
针对您遇到的错误,提示需要下载C++构建工具,我也曾遇到过同样的问题。我尝试了下载Microsoft Visual Studio运行库,但并没有解决问题。后来我下载了带有Anaconda插件的PyCharm社区版,并下载了Anaconda,激活后使用conda的python.exe配置了一个conda解释器。然后我输入以下命令: conda install PyAudio 这样就成功安装了所有必要的组件。我建议您也可以尝试这种方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接