Your original code is close; what might be happening is your source variable could have the write scope of the with … as source:
block. By ending the with
block; you're also unsetting the variables created for that block. If this is the issue, you could:
- Create your variables at the script scope (i.e. not within any conditional blocks, such as after
r = sr.Recognizer()
), and only assign it value within the with
block
import speech_recognition as sr
r = sr.Recognizer()
audio = False
with sr.AudioFile("hello_world.wav") as source:
audio = r.record(source)
try:
s = r.recognize_google(audio)
print("Text: "+s)
except Exception as e:
print("Exception: "+str(e))
- Perform all your processing while the audio file is in-scope
import speech_recognition as sr
r = sr.Recognizer()
with sr.AudioFile("hello_world.wav") as source:
audio = r.record(source)
try:
s = r.recognize_google(audio)
print("Text: "+s)
except Exception as e:
print("Exception: "+str(e))
- As you've done in the accepted solution above; remove the
with
block and flatten your code structure.
import speech_recognition as sr
r = sr.Recognizer()
audio = r.record(sr.AudioFile("hello_world.wav"))
try:
s = r.recognize_google(audio)
print("Text: "+s)
except Exception as e:
print("Exception: "+str(e))