20

I'm trying to make a basic speech Recognition assistant. When I run the code, it tells me:

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 

I tried to pip install pyaudio but then this error shows up:

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()
Adrian W
  • 4,563
  • 11
  • 38
  • 52
Mo .haytham
  • 231
  • 1
  • 2
  • 7

11 Answers11

41

In Terminal type

pip install pipwin

Then

pipwin install pyaudio
Liam
  • 27,717
  • 28
  • 128
  • 190
user3248990
  • 434
  • 5
  • 5
8

If you are ubuntu 18.04 user follow these steps

sudo apt-get install portaudio19-dev python-pyaudio

Then

pip install PyAudio
rupesh
  • 471
  • 5
  • 5
5

I've also found PyAudio installation can be a pain, even a deal-breaker for some end-users, because of installation difficulties. In principle there's no reason why speech_recognition.Recognizer.listen() couldn't take its input from other audio libraries such as sounddevice or soundcard or audiomath, all of which are usually easier to install. Luckily, although the speech_recognition code itself only provides PyAudio implementations, internally it requires only a few attributes of Microphone to be duck-typed to allow it to listen() successfully. Specifically:

  • source must be an instance of a speech_recognition.AudioSource subclass
  • source.stream must be non-None while the source is active
  • source.CHUNK must be the (integer) number of samples per chunk
  • source.SAMPLE_RATE must be the sampling rate
  • source.SAMPLE_WIDTH must be the number of bytes per sample
  • source.stream.read(numberOfSamples) must return raw single-channel audio data

Here is a duck-typed solution using 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()
jez
  • 14,867
  • 5
  • 37
  • 64
3

You are getting error of installing pyaudio because you don't have c++ building tools to install pyaudio.

For installing Mircosoft visual C++ 14.0 consider this link https://stackoverflow.com/a/49986365/8227403

then, Install pyaudio.

if you are using jupyter notebook on anaconda prompt then

conda install pyaudio

if you are using jupyter notebook using cmd then on jupyter cell,

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

if you are running python file on cmd then,

pip3 install pyaudio #for python3
user99
  • 157
  • 1
  • 4
1

It appears you are missing some required files to build pyaudio.

From your error log,

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

You'll need to install Microsoft Visual C++ Build Tools

1

I was facing issue even after installing pipwin so I found the solution execute below before installing PyAudio

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

steps to install pyaudio and portaudio on Mac M1

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"
ChrisDanger
  • 1,071
  • 11
  • 10
0

sudo apt-get install libportaudio-dev (first try with this) sudo apt-get install portaudio19-dev (instead use this) later install pyaudio (python -m pip install PyAudio)

Nikhil08
  • 31
  • 1
0

For your error that said download the C++ build tools, I had the same error. I the downloaded the Microsoft visual studio runtime and it didn't work. I then downloaded pycharm community edition with anaconda plugin. I downloaded anaconda, activated it and then configured a conda interpreter with conda's python.exe. I then types the following: conda install PyAudio And it installed everything just fine for me. I would recommend doing this.

0

If you are a macOS user

Install portaudio

brew install portaudio

Then install pyaudio

pip install pyaudio 
Ashok Kumar
  • 411
  • 4
  • 2
-1

PyAudio is supported in Python 2.7, 3.4, 3.5, and 3.6 (in both 32-bit and 64-bit). You probably have to install any of the above python for PyAudio to work.

Pranav
  • 66
  • 2