My code is working but I'm looking to improve performance.
The issues:
- Sometimes there is a delay, the code is stuck and the user needs to wait a long time for a response.
- 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?