0

I was trying to make a text to speech module in python using my microphone ,but when I run the program , it throws the error.Here is my code:

import pyttsx3
import speech_recognition as sr
import webbrowser
import datetime
import pyjokes

def sptext():
    # Create a recognizer instance
    recognizer = sr.Recognizer()

    # Use the default microphone as the audio source
    with sr.Microphone() as source:
        print("Listening...")

        try:
            # Adjust for ambient noise before listening
            recognizer.adjust_for_ambient_noise(source)

            audio = recognizer.listen(source)

            # Use Google Speech Recognition to transcribe the audio to text
            text = recognizer.recognize_google(audio)
            print(f"You said: {text}")
        except sr.UnknownValueError:
            print("Sorry, I could not understand what you said.")
        except sr.RequestError as e:
            print(f"Request error: {e}")
        
        try:
            # Close the audio stream
            source.stream.close()
        except AttributeError:
            pass


sptext()

error I get is

During handling of the above exception, another exception occurred:   

Traceback (most recent call last):  File "C:\computer_science\Python Lessons\Projects\7-Voice Assitant\ch1\main.py", line 68, in <module>
    sptext()  File "C:\computer_science\Python Lessons\Projects\7-Voice Assitant\ch1\main.py", line 44, in sptext
    with sr.Microphone() as source:
  File "C:\Users\Asus\AppData\Roaming\Python\Python311\site-packages\speech_recognition\__init__.py", line 189, in __exit__
    self.stream.close()
    ^^^^^^^^^^^^^^^^^AttributeError: 'NoneType' object has no attribute 'close'

Trying to make a speech to text project in python using speechRecognition module but somehow I don't know whats wrong with my code?

desertnaut
  • 57,590
  • 26
  • 140
  • 166

1 Answers1

0

When you're using the with ... as ... pattern, you don't have to .close(). See, e.g., this answer for more information.