Uberi / speech_recognition

Speech recognition module for Python, supporting several engines and APIs, online and offline.

Home Page:https://pypi.python.org/pypi/SpeechRecognition/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Error when running simple speech recognition code

General-Hex opened this issue · comments

Steps to reproduce

Running this code:

import speech_recognition as sr
import pyttsx3
import webbrowser
import wikipedia
import wolframalpha
import os
from termcolor import colored, cprint


ENGINE = pyttsx3.init('dummy')
VOICES = ENGINE.getProperty('voices')
ENGINE.setProperty('voice', VOICES[0].id)
ACTIVATION_WORD = "echo"

def Command_recognition():
    listener = sr.Recognizer()
    os.system('clear')
    activated_text = colored('ACTIVATED','light_green', attrs=['blink', 'bold'])
    print(activated_text)
    
    with sr.Microphone(device_index=1) as source:
        listener.pause_threshold = 2
        command = listener.listen(source)
    
    try:
        listening_text = colored('LISTENING...','light_green', attrs=['blink'])
        print(listening_text)
        query = listener.recognize_google_cloud(command, language='en_gb')
    except Exception as exception:
        error_text = colored('ERROR','red', attrs=['blink', 'bold'])
        print('\n'+error_text)
        print(exception)
        quit()
    return query


query1 = Command_recognition()
print(query1)

Expected behaviour

Run normally without issues and print speech input

Actual behaviour

crashed with this error code:
||PaMacCore (AUHAL)|| AUHAL component not found.Traceback (most recent call last):
File "/Users/ryan/Desktop/stuff/code/Project Echo/main.py", line 29, in Command_recognition
command = listener.listen(source)
^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/ryan/anaconda3/lib/python3.11/site-packages/speech_recognition/init.py", line 466, in listen
assert source.stream is not None, "Audio source must be entered before listening, see documentation for AudioSource; are you using source outside of a with statement?"
AssertionError: Audio source must be entered before listening, see documentation for AudioSource; are you using source outside of a with statement?

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/ryan/Desktop/stuff/code/Project Echo/main.py", line 43, in
query1 = Command_recognition()
^^^^^^^^^^^^^^^^^^^^^
File "/Users/ryan/Desktop/stuff/code/Project Echo/main.py", line 27, in Command_recognition
with sr.Microphone(device_index=1) as source:
File "/Users/ryan/anaconda3/lib/python3.11/site-packages/speech_recognition/init.py", line 189, in exit
self.stream.close()
^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'close'

System information

(Delete all the statements that don't apply.)

My MacOS Sonoma 14.4.1

My Python version is 3.11.0

My Pip version is 23.1.2

My SpeechRecognition library version is 3.10.3

My PyAudio library version is 0.2.14

My microphones are: ['Ryan’s iPhone 15 Pro Microphone', 'MacBook Pro Microphone', 'MacBook Pro Speakers']

My working microphones are: the code outputs this: ||PaMacCore (AUHAL)|| AUHAL component not found.||PaMacCore (AUHAL)|| AUHAL component not found.{}

Also to note I am using a Anaconda environment

Hey @General-Hex,
This error typically indicates issues in accessing the audio hardware.
To resolve this, please ensure that your audio hardware is properly connected and configured. Also, make sure that your device isn't blocking the access request.

For further reference and potential solutions, you can check out this discussion on GitHub: Link to the issue.

Hey @General-Hex, This error typically indicates issues in accessing the audio hardware. To resolve this, please ensure that your audio hardware is properly connected and configured. Also, make sure that your device isn't blocking the access request.

I’ve tried everything, I’m only using the inbuilt microphone of the MacBook and I have given both terminal and VScode all possible permissions including full disk access and microphone access still to no avail

@thedarknight01 None of those solutions have worked for me, do you have any specific solutions for me to try?

@thedarknight01 I also tried disabling all firewalls/filters, giving all permissions to vscode and terminal and also connecting a seperate microphone and using that device index to no avail. I tried uninstalling and reinstalling speech recognition, pyaudio and portaudio again to no avail. Apparently many people on macbooks (Mainly on M-chip series) are having this issue, is there any specific solution that has worked for them?

Please attempt these commands as the standard installation seems to be encountering issues. This alternative method often resolves many problems.

brew uninstall portaudio
brew install portaudio --HEAD

@thedarknight01 I’ve tried that multiple times sadly to no success. This is very frustrating because I had a plan for a super cool project but it isn’t possible without speech recognition. What else can I try?

I apologize for the inconvenience; I was having the same problem, which I resolved with the step. I'm unsure why, this is not working but don't worry—I'll figure something out.

@thedarknight01 thank you. Also I fully understand that this is not your fault and out of your control because apple probably did some sort of silly update that messed with things. let me know if there is any tests/anything else you would like me to try 😊

@General-Hex these are some steps provided by ai please also try this

  1. Upgrade PyAudio:

The most effective solution is to upgrade PyAudio to a version compatible with Apple Silicon. There are two main approaches:

Upgrade using pip (recommended):


conda install -c conda-forge pyaudio

Upgrade using brew (if you have Homebrew):

brew update
brew install portaudio
  1. Check for Conflicting PyAudio Installations:

If you have multiple Python environments, ensure you're installing PyAudio into the correct one. You can verify the active environment using:

conda info --envs

If you suspect conflicting installations, consider creating a new virtual environment for your project and installing PyAudio there.

  1. Reinstall SpeechRecognition:

After upgrading PyAudio, reinstall SpeechRecognition to ensure compatibility changes are reflected:

pip install --upgrade speechrecognition
  1. Additional Considerations (if issues persist):

Security and Privacy Settings: On macOS Ventura or later, ensure your app has microphone access granted in System Settings > Security & Privacy > Privacy > Microphone.
PortAudio Version: If the conda install command doesn't work, try a specific PyAudio version compatible with Apple Silicon (e.g., pip install pyaudio==0.2.13).

Let me try those now and get back to you

can't install pyaudio with the first command, gives this error:

Retrieving notices: ...working... done
Channels:
 - conda-forge
 - defaults
Platform: osx-arm64
Collecting package metadata (repodata.json): done
Solving environment: failed

PackagesNotFoundError: The following packages are not available from current channels:

  - pyaudio

Current channels:

  - https://conda.anaconda.org/conda-forge
  - defaults

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.``` 

try after updating the conda

conda update conda

Also, I have checked on Internet and there could be a problem of environment
are you using any virtual env for conda ??

IT WORKED, I don't know what did it but it finally worked, this is what i did:

  1. fully uninstalled portaudio, pyaudio and speech recognition.
  2. ran brew update && brew install portaudio --HEAD
  3. ran python -m pip install pyaudio --no-cache
  4. ran python -m pip install speechrecognition

and IT WORKED

only problem is that now for some reason this line is giving an error but not saying what the error is:
query = listener.recognize_google_cloud(command, language='en_gb')

oh because I need an account and its paid, i'll probably use openai whisper for that then but thank you very much 😊 (hopefully other people with this issue can solve it too)

OMG as soon as I closed the issue and tried to run the code again IN THE EXACT SAME WAY it starting throwing the attribute error again

@General-Hex I was about to suggest that authenticity may be the problem.
Now if your issue is solved please close the issue.
Happy Coding 😊.

@thedarknight01 the error started again, I changed NOTHING, it just stopped working all of a sudden

the attribute error that is with not being able to use my microphone, not the account error

Please try to update the conda and try with minimal code to avoid complexity which will clear the problem causing culprit.

@thedarknight01 I just updated my conda, could you give me a simple code to copy and paste to try because i'm currently using my original code (in my original issue post) which is only 47 lines long

its strange because it began working for 3 times i ran the code, then as soon as I closed this issue and tired one last time it failed

@thedarknight01 I SOLVED IT

the problem is that your iphone keeps connecting/disconnecting from your macbook meaning it keeps going into index 0 of the list of devices.

@thedarknight01 adding these lines of code should stop the issue for others too (but changing the name with the name of their own phone ofc):

devices = sr.Microphone.list_microphone_names()
    if devices[0] == 'Ryan’s iPhone 15 Pro Microphone': index = 1
    else: index = 0
    with sr.Microphone(device_index=index) as source:```

devices = sr.Microphone.list_microphone_names()
print(devices)
run this check the name of your microphone and replace it from there

I have before that is how I found the error, it gives the following:
['MacBook Pro Microphone', 'MacBook Pro Speakers'] or ['Ryan’s iPhone 15 Pro Microphone', 'MacBook Pro Microphone', 'MacBook Pro Speakers'] depending if my phone is connected or not which randomly changes