-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvoice_handler.py
More file actions
58 lines (47 loc) · 1.94 KB
/
Copy pathvoice_handler.py
File metadata and controls
58 lines (47 loc) · 1.94 KB
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
50
51
52
53
54
55
56
57
58
import speech_recognition as sr
import threading
import pyautogui
class VoiceHandler:
def __init__(self, status_callback=None):
self.recognizer = sr.Recognizer()
self.microphone = sr.Microphone()
self.is_listening = False
self.stop_listening_func = None
self.status_callback = status_callback
# Adjust for ambient noise once at startup (optional, can be slow)
# with self.microphone as source:
# self.recognizer.adjust_for_ambient_noise(source)
def start_listening(self):
if self.is_listening:
return
self.is_listening = True
if self.status_callback:
self.status_callback("Voice listening started...")
# Create a fresh Microphone to avoid "already inside context manager"
self.microphone = sr.Microphone()
# listen_in_background spawns a daemon thread
self.stop_listening_func = self.recognizer.listen_in_background(
self.microphone,
self.callback
)
def stop_listening(self):
if self.stop_listening_func:
self.stop_listening_func(wait_for_stop=False)
self.stop_listening_func = None
self.is_listening = False
if self.status_callback:
self.status_callback("Voice listening stopped.")
def callback(self, recognizer, audio):
try:
# Recognize speech using Google Speech Recognition
text = recognizer.recognize_google(audio)
if self.status_callback:
self.status_callback(f"Heard: {text}")
# Type the text
pyautogui.write(text + " ")
except sr.UnknownValueError:
# print("Google Speech Recognition could not understand audio")
pass
except sr.RequestError as e:
if self.status_callback:
self.status_callback(f"Could not request results; {e}")