[Python] What is Wrong with this code it is unable to take command as speech in python

Discussão em 'Python' iniciado por Stack, Abril 15, 2025.

  1. Stack

    Stack Membro Participativo

    import speech_recognition as sr
    import win32com.client
    import pyttsx3

    speaker = win32com.client.Dispatch("SAPI.SpVoice")


    def say(text):
    print("Speaking......")
    speaker.Speak(text)


    def take_command():
    r = sr.Recognizer()
    with sr.Microphone() as source:
    r.pause_threshold = 1
    audio = r.listen(source)
    try:
    query = r.recognize_google(audio, language='en-in')
    print(f"User said: {query}")
    return query
    except Exception as e:
    print(e)
    return "Sorry from Jarvis"


    if __name__ == '__main__':
    say("Hello, I am Jarvis A.I.")
    while True:
    print("Listening....")
    text = take_command()
    say(text)


    The above Python program is throwing an error message while executing the take_command() function. The program is built to run speech recognition on commands, and execute the voice command on the computer. Can anyone help me understand what is causing this error and how to resolve it? Thanks in advance.

    Error:

    Traceback (most recent call last):
    File "C:\Users\Arpit Singh\PycharmProjects\AIJarvis\main.py", line 18, in take_command
    audio = r.listen(source)
    ^^^^^^^^^^^^^^^^
    File "C:\Users\Arpit Singh\PycharmProjects\AIJarvis\venv\Lib\site-packages\speech_recognition\__init__.py", line 465, 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 "C:\Users\Arpit Singh\PycharmProjects\AIJarvis\main.py", line 32, in <module>
    text = take_command()
    ^^^^^^^^^^^^^
    File "C:\Users\Arpit Singh\PycharmProjects\AIJarvis\main.py", line 15, in take_command
    with sr.Microphone() as source:
    File "C:\Users\Arpit Singh\PycharmProjects\AIJarvis\venv\Lib\site-packages\speech_recognition\__init__.py", line 189, in __exit__
    self.stream.close()
    ^^^^^^^^^^^^^^^^^
    AttributeError: 'NoneType' object has no attribute 'close'

    Continue reading...

Compartilhe esta Página