File size: 1,269 Bytes
67a1325 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | import speech_recognition as sr
import pyttsx3
_engine = None
def _get_engine():
global _engine
if _engine is None:
_engine = pyttsx3.init()
_engine.setProperty("rate", 175) # slightly faster speech
return _engine
def speak(text):
print(f"Sunday: {text}")
try:
eng = _get_engine()
eng.say(text)
eng.runAndWait()
except Exception:
pass
def listen():
r = sr.Recognizer()
r.pause_threshold = 0.8 # stop listening after 0.8s of silence
try:
with sr.Microphone() as source:
print("Listening...")
r.adjust_for_ambient_noise(source, duration=0.5)
audio = r.listen(source, timeout=5, phrase_time_limit=10)
text = r.recognize_google(audio)
print(f"You: {text}")
return text
except sr.WaitTimeoutError:
print("[No speech detected]")
return ""
except sr.UnknownValueError:
print("[Couldn't understand, try again]")
return ""
except sr.RequestError:
print("[Mic/network error — switching to text input]")
return None # None signals caller to fall back to keyboard
except Exception:
return "" |