Search code examples
pythonspeech-recognition

Python speech_recognition IF Speech not recognised


I am a Portuguese High Schooler so sorry if I dont make myself very clear but I will try my best to explain my problem. So for this project I need to make a program that recognises speech and do what is told to do. But if the speech is not recognisable I want the program to try until it finally catches what is being said. However I dont really know how to do that since this "error" keeps appearing: Error

Here is the code if anyone wants to help:

import speech_recognition as sr
import subprocess as sp
import os

def ouvir_microfone():

   audio_Input = sr.Recognizer()

   with sr.Microphone() as source:
           
               Ray = "ON"
               Open = "Open"

               print("Hello my name is Ray pleased to help you")

               audio_Input.adjust_for_ambient_noise(source)
               print("Say something: ")
               audio = audio_Input.listen(source)
               
               frase = audio_Input.recognize_google(audio,language='en-US')

               if ValueError: print("Speech not recognised")
               else: print("You said: " + frase)

               if Open in frase:
                   print('sucess') 
ouvir_microfone()

Solution

  • import speech_recognition as sr
    import subprocess as sp
    import os
    
    def ouvir_microfone():
    
        audio_Input = sr.Recognizer()
    
        with sr.Microphone() as source:
            
            Ray = "ON"
            Open = "Open"
    
            print("Hello my name is Ray pleased to help you")
    
            audio_Input.adjust_for_ambient_noise(source)
            print("Say something: ")
            audio = audio_Input.listen(source)
            try:
                # valid
                frase = audio_Input.recognize_google(audio,language='en-US')
                print("You said: " + frase)
            except: 
                # google could not validate
                print("Speech not recognised")
                return False
    
            if Open in frase:
                print('sucess') 
            return True
    while True:
        if ouvir_microfone():
            # got a valid response
            break
    

    Works as a solid template. Some imports also remain unused as a sidenote. Catch the exception and return False if the speech could not be recognized so it retries. The google voice recognition python library throws an exception in the case that no distinguishable speech can be read.