0
import speech_recognition as sr

r = sr.Recognizer()

with sr.Microphone as source:
   print("Say something")
   audio = r.listen(source)
   voice_data = r.recognize_google(audio)
   print(voice_data)

I am trying to compiling this code but it gives error like this :-

Exception has occurred: AttributeError
__enter__
File "C:\Users\admin\Desktop\text to speech\speech to text.py", line 5, in 
<module>
with sr.Microphone as source:

5 Answers 5

1

Every object used in a context manager, should have an __enter__ method and an __exit__ method implemented in its class. The object you are using, sr.Microphone, is an instance of a class that doesn't implement them. To solve this, you should either not use a context manager (don't use the with), or implement the __enter__ and __exit__ methods for sr.Microphone's class. You can find a detailed explanation about context managers in the Python documentation, or a shorter one here.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you please explain it in detail
The only thing 'with' does, is calling the object's (sr.Microphone, in this case) __enter__ method upon entering the with's scope, and calling the __exit__ method upon exiting it. In case the method __enter__ (or __exit__) does not exist - you get an AttributeError indicating that the method __enter__ does not exist, just like you got
1

You just need to use sr.Microphone() you've forgot paranthesis. Remember microphone is a method.

Comments

0

It looks like you have incorrect intention. Try running after fixing indentaion:

import speech_recognition as sr

r = sr.Recognizer()

with sr.Microphone as source:
  print("Say something")
  audio = r.listen(source)
  voice_data = r.recognize_google(audio)
  print(voice_data)

Comments

0

As @motyzk answered, the context manager should have an enter method and an exit method implemented in its class. But I believe sr.Microphone already have it. Please check if you have installed all the required libraries

Comments

0

I know this is kind of late, but try using sr.Microphone() instead of sr.Microphone

>>> import speech_recognition as sr
>>> type(sr.Microphone)
<class 'type'>
>>> type(sr.Microphone())
<class 'speech_recognition.Microphone'>

Here you can see the difference between sr.Microphone() and sr.Microphone, as one is a type, and one is an actual instance of that type.

The type itself doesn't have methods for use in a context manager, but an instance of the class does.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.