Search code examples
pythonartificial-intelligencespeech-recognitiongoogle-assistant

Im making a virtual Assitant on python and i dont know why speech recognition doesnt listening and prints the what i have said


So as I said I'm making a Virtual Assistant using Python and speech recognition doesn't listen to me it doesn't print what I have said. Below is the code:

import speech_recognition as sr

def get_audio():
    print("listening...")
    r = sr.Recognizer()
    with sr.Microphone() as source:
        audio = r.listen(source)
        said = ""

        try:
            said = r.recognize_google(audio)
            print(said)
        except Exception as e:
            print("Exception: " + str(e))
        
    return said


get_audio()

And after I run and debug the code as python it only says me listening to I talk as loud as I can on the microphone but don't work. My task bar shows that python is using a microphone but still don't work and I'm using vscode.

Please everyone who can help me.


Solution

  • Apparently, based on your description, your code keeps on listening and I think that's the problem. Now I'll give an updated code below

    import speech_recognition as sr
    
    def get_audio():
        print("listening...")
        r = sr.Recognizer()
        with sr.Microphone() as source:
            r.adjust_for_ambient_noise(source, duration = 1)
            audio = r.listen(source)
            said = ""
    
            try:
                said = r.recognize_google(audio)
                print(said)
    
            except Exception as e:
                print("Exception: " + str(e))
            
        return said
    
    
    get_audio()
    

    So I've added the r.adjust_for_ambient_noise(source, duration = 1) what it does is that, it adjusts the threshold according to the background noises, and then listens to whatever you say.

    This should work fine!