Python speech recognition: recognize_google with UnknownValueError for Microphone

my question is about the speech recognition using Python. My code is supposed to listen to what I say to the microphone (having 5 seconds to say my message) and then print out whatever it understood.

import speech_recognition as sr

r = sr.Recognizer()
mic = sr.Microphone()

with mic as audio:
    print("Speak Please")

    r.adjust_for_ambient_noise(audio)
    audio = r.record(audio, duration=5)

    print("Converting Speech to Text...")
    print("You said: " + r.recognize_google(audio))

But I always get the error message:

File "/opt/anaconda3/lib/python3.8/site-packages/speech_recognition/__init__.py", line 780, in recognize_google
    if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()
speech_recognition.UnknownValueError

I tried to use audio files I found online and r.recognize_google worked fine. But once I use my microphone I always get an error. I also tried switching between “record” and “listen”, without any success. Has anybody encountered a similar problem and knows what might be wrong?

Edit: Using an except block like:

try:
   print("You said: {}".format(r.recognize_google(audio,language='en-USA')))
except:
   print("Couldn't hear you")

Also does not help, it just throws the exception every time.

Any help is appreciated.

Thank you very much!

Answer

So I managed to solve the problem. Apparently it’s a problem with Visual Studio Code. I had to run the code from the terminal, and now it is working fine. Im not sure why this is the case, but I’m happy that it is working now.