sunai / code /voice.py
kartik20032003's picture
Upload code/voice.py with huggingface_hub
67a1325 verified
Raw History Blame Contribute Delete
1.27 kB
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 ""