Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (19.9k points)

I have the following python code:

import speech_recognition as sr

recognizer=sr.Recognizer()

mic=sr.Microphone()

print('Heyyyaa')

audio=recognizer.listen(mic)

try:

    text=recognizer.recognize_google(language='it')

    print('heyyya '+text)

except sr.UnknownValueError:

    print('Errore 1')

except sr.RequestError:

    print('Errore 2')

I get the following error:

Traceback (most recent call last):

  File "C:/Users/Freddy/PycharmProjects/SpeechRecognition/SpeechToText.py", line 26, in <module>

    audio=recognizer.listen(mic)

  File "C:\Python34\lib\site-packages\speech_recognition\__init__.py", line 293, in listen

    buffer = source.stream.read(source.CHUNK)

AttributeError: 'NoneType' object has no attribute 'read'

1 Answer

0 votes
by (25.1k points)

You are getting this error because you are not not instantiating the microphone in a  context manager. 

To put it simply a context manager simply means a 'with' statement or a statement that begins with the with keyword. It helps in wrapping a piece of code helps in performing some tasks before and after it, like freeing up some resource. 
You can do it like this:

import speech_recognition

recognizer=speech_recognition.Recognizer()

with speech_recognition.Microphone() as microphone:

    print('Yes')

    audio=recognizer.listen(microphone)

try:

    text=recognizer.recognize_google(language='it')

    print('Text: '+text)

except speech_recognition.UnknownValueError:

    print('Unknown Value')

except speech_recognition.RequestError:

    print('Invalid Request')

In case you wish to learn more about python use this video:

Browse Categories

...