Peker Çelik
Peker Çelik

Reputation: 19

Getting AttributeError: __enter__ when using Microphone from Speech Recognizer

The code is below. As I researched the documention Speech_Recognision must be installed if we use Microphone. So I installed it but still i have this error.

def recordAudio():

r = sr.Recognizer()

with sr.Microphone as source:
    print('I am listening to you sir.')
    audio = r.listen(source)
    data = ''

try:
    data = r.recognize_google(audio)
    print('You said: ' + data)
except sr.UnknownValueError:
    print('Voice cannot be recognized.')
except sr.RequestError as e:
    print('Req results:' + e)

return data

line 54, in recordAudio with sr.Microphone as source: AttributeError: __enter__

Upvotes: 1

Views: 1720

Answers (3)

Vritika Malhotra
Vritika Malhotra

Reputation: 369

For all those who did not get solution to this problem:

Instead of using the class sr.Microphone as a source, use the object sr.Microphone().

Because we are supposed to call the method using the speechRecognition object and not the class itself.

Upvotes: 1

Olivier Melançon
Olivier Melançon

Reputation: 22294

An AttributeError: __enter__ means you are attempting to enter a context manager block with an object which does not support the context manager protocol; it does not have a __enter__ method.

Specifically, you are attempting to open the sr.Microphone class in you with statement. As per the documentation, you need to provide an instance sr.Microphone() to the context manager instead.

with sr.Microphone() as source:
    ...

Upvotes: 3

Mahsa Hassankashi
Mahsa Hassankashi

Reputation: 2139

It would constantly listen until you terminate: SpeechRecognition

import speech_recognition as sr

def speech_recog():
    r = sr.Recognizer()

    mic = sr.Microphone()
    while True:
        with mic as source:
            print("Speak...")

            audio = r.listen(source)

            try:
                text = r.recognize_google(audio)
                print(f"You said {text}")

            except sr.UnknownValueError:
                print("Didnt hear that try again")
speech_recog()

Upvotes: 0

Related Questions