-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
121 lines (106 loc) · 4.54 KB
/
Copy pathapp.py
File metadata and controls
121 lines (106 loc) · 4.54 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import tkinter as tk
import sounddevice as sd
import numpy as np
import speech_recognition as sr
import subprocess
import os
import threading
def execute_command(command):
"""
Checks for keywords in the recognized text and executes the corresponding command.
"""
command = command.lower()
if "notepad" in command:
result_label.config(text="Opening Notepad...")
try:
subprocess.Popen("notepad")
except Exception as e:
result_label.config(text=f"Failed to open Notepad: {e}")
elif "calculator" in command or "calc" in command:
result_label.config(text="Opening Calculator...")
try:
subprocess.Popen("calc")
except Exception as e:
result_label.config(text=f"Failed to open Calculator: {e}")
elif "shutdown" in command:
result_label.config(text="Shutting down system...")
os.system("shutdown /s /t 1")
elif "restart" in command:
result_label.config(text="Restarting system...")
os.system("shutdown /r /t 1")
else:
result_label.config(text="Command not recognized.")
def record_and_recognize():
"""
Records audio for a fixed duration (e.g., 5 seconds) and then uses Google Speech Recognition
to convert it to text. The recognized text is displayed in the GUI and printed to the console.
"""
sample_rate = 16000 # You may try 44100 if 16000 doesn't work well.
duration = 5 # seconds
status_label.config(text="Recording for 5 seconds... Speak now!")
print("Recording for 5 seconds...")
try:
recording = sd.rec(int(duration * sample_rate), samplerate=sample_rate, channels=1, dtype='int16')
sd.wait() # Wait until the recording is finished
except Exception as e:
status_label.config(text=f"Recording error: {e}")
print("Recording error:", e)
record_button.config(state=tk.NORMAL)
stop_button.config(state=tk.DISABLED)
return
status_label.config(text="Stopped recording. Processing audio...")
print("Recording complete. Processing audio...")
# Convert the numpy array to bytes
audio_data_bytes = recording.tobytes()
sample_width = 2 # int16 = 2 bytes
recognizer = sr.Recognizer()
audio_data = sr.AudioData(audio_data_bytes, sample_rate, sample_width)
try:
recognized_text = recognizer.recognize_google(audio_data)
command_label.config(text="You said: " + recognized_text)
print("You said:", recognized_text)
status_label.config(text="Processing command...")
execute_command(recognized_text)
except sr.UnknownValueError:
status_label.config(text="Could not understand the audio.")
print("Could not understand the audio.")
except sr.RequestError as e:
status_label.config(text=f"Request error: {e}")
print("Request error:", e)
except Exception as e:
status_label.config(text=f"Error during recognition: {e}")
print("Error during recognition:", e)
finally:
record_button.config(state=tk.NORMAL)
stop_button.config(state=tk.DISABLED)
def start_recording():
"""
Called when the Record button is pressed. Disables the Record button,
enables the Stop button (though in this fixed-duration version it may not be used),
and starts the recording process in a new thread.
"""
record_button.config(state=tk.DISABLED)
stop_button.config(state=tk.DISABLED) # Not used in fixed-duration mode
threading.Thread(target=record_and_recognize, daemon=True).start()
# ---------------------------
# GUI Setup with Tkinter
# ---------------------------
root = tk.Tk()
root.title("Voice Command Recorder (Fixed Duration)")
root.geometry("500x300")
# Label to display the recognized speech
command_label = tk.Label(root, text="Your command will appear here", font=("Helvetica", 12))
command_label.pack(pady=10)
# Label for status messages (Recording status, errors, etc.)
status_label = tk.Label(root, text="Press Record and speak", font=("Helvetica", 10))
status_label.pack(pady=5)
# Label to display the result of any executed system command
result_label = tk.Label(root, text="", font=("Helvetica", 12))
result_label.pack(pady=5)
# Button to start recording
record_button = tk.Button(root, text="Record", font=("Helvetica", 12), command=start_recording)
record_button.pack(pady=10)
# (In this fixed-duration version, the Stop button is not used, but we include it for consistency.)
stop_button = tk.Button(root, text="Stop", font=("Helvetica", 12), state=tk.DISABLED)
stop_button.pack(pady=10)
root.mainloop()