improve speechrecognition, python

Viewed 598

My code is working but I'm looking to improve performance.

The issues:

  1. Sometimes there is a delay, the code is stuck and the user needs to wait a long time for a response.
  2. Sometimes the code can't recognize the voice, or it recognizes the voice correctly but nothing happens.

My code:

import speech_recognition as sr
import keyboard
import os
import time


def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone(device_index=2) as source:
        print("Listening...")
        r.pause_threshold = 1
        try:
            audio = r.listen(source, timeout=2)
        except sr.WaitTimeoutError as e:
            return "None"
    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language='en-in')
        print(f"User said: {query}\n")

    except Exception as e:
        print(e)
        print("Unable to Recognizing your voice.")
        return "None"

    return query


if __name__ == '__main__':
    clear = lambda: os.system('cls')
    clear()
    while True:
      query = takeCommand().lower()
      # Do something with query

Is there anything I can do to improve?

2 Answers

Try this block of code. It is more optimised and still does the purpose. And you can set the listening time by changing phrase_time_limit.

def myCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        audio = r.listen(source, phrase_time_limit = 5)  
    try:
        command = r.recognize_google(audio).lower()
        print("you said: " + command)
        
    except sr.UnknownValueError:
        print("Sorry, Cant understand, Please say again")
        command = myCommand()
    return command

You should check your microphone as there may be problems in the audio signal or you can try other alternatives like - apiai, wit, google-cloud-speech and pocketsphinx.

Your code looks fine.

Related