Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Script to Shutdown your PC using Voice Commands
In today's world of automation and smart devices, voice control has become increasingly popular. From smartphones to virtual assistants, voice commands offer a convenient and handsfree way to interact with technology. What if you could extend this convenience to your PC as well? Imagine being able to shut down your computer with a simple voice command, saving you the trouble of manually navigating through menus or using the mouse.
In this article, we will explore how to use Python to create a script that allows you to shut down your PC using voice commands. By leveraging the power of speech recognition technology, we can harness the flexibility and ease of voice control to automate the process of shutting down your computer.
Setting up the Environment
Before we dive into coding our script, let's make sure we have the necessary tools and libraries set up. Here are the steps to get started
Install Required Libraries
We'll be using the SpeechRecognition library to convert spoken words into text. Open a command prompt or terminal and run the following commands
pip install SpeechRecognition pip install PyAudio
Note: PyAudio is required for capturing audio from your microphone. On some systems, you may need to install additional system dependencies.
Test the Installation
To verify that the SpeechRecognition library is installed correctly, let's write a simple test script
import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source:
print("Speak something...")
audio = r.listen(source)
try:
text = r.recognize_google(audio)
print(f"You said: {text}")
except sr.UnknownValueError:
print("Sorry, I could not understand your speech.")
except sr.RequestError as e:
print(f"An error occurred: {e}")
Save this as test_voice_recognition.py and run it. Speak something into your microphone, and if everything is set up correctly, you should see the recognized text printed on the screen.
Implementing the VoiceControlled Shutdown Script
Now that we have our environment set up, let's dive into implementing the voicecontrolled shutdown script using Python. The script will listen for specific voice commands and initiate the shutdown process when the command is recognized.
Complete Script
Here's the complete voicecontrolled shutdown script
import speech_recognition as sr
import os
import sys
import platform
def shutdown_computer():
"""Shutdown the computer based on the operating system"""
system = platform.system()
if system == "Windows":
os.system("shutdown /s /t 0")
elif system == "Linux" or system == "Darwin": # Darwin is macOS
os.system("sudo shutdown -h now")
else:
print("Unsupported operating system")
def listen_for_commands():
"""Listen for voice commands and execute actions"""
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening for commands...")
print("Say 'shutdown my computer' to shutdown")
print("Say 'exit' to quit the program")
# Adjust for ambient noise
r.adjust_for_ambient_noise(source)
audio = r.listen(source, timeout=10)
try:
text = r.recognize_google(audio).lower()
print(f"You said: {text}")
if "shutdown my computer" in text or "shutdown computer" in text:
print("Shutting down your computer...")
shutdown_computer()
elif "exit" in text or "quit" in text:
print("Goodbye!")
sys.exit()
else:
print("Command not recognized. Try saying 'shutdown my computer'")
except sr.UnknownValueError:
print("Sorry, I could not understand your speech.")
except sr.RequestError as e:
print(f"Could not request results from speech service: {e}")
except sr.WaitTimeoutError:
print("Listening timeout. No speech detected.")
def main():
"""Main function to run the voice command loop"""
print("VoiceControlled PC Shutdown Script")
print("Make sure your microphone is working properly")
print("" * 40)
while True:
try:
listen_for_commands()
except KeyboardInterrupt:
print("\nProgram interrupted by user. Goodbye!")
break
if __name__ == "__main__":
main()
How It Works
Speech Recognition: The script uses Google's speech recognition service to convert spoken words into text
CrossPlatform Support: The shutdown command works on Windows, Linux, and macOS
Ambient Noise Adjustment: The script automatically adjusts for background noise
Error Handling: Comprehensive error handling for speech recognition issues
Continuous Listening: The script runs in a loop, continuously listening for commands
Enhanced Version with Confirmation
For safety, here's an enhanced version that asks for confirmation before shutting down
import speech_recognition as sr
import os
import platform
import time
def shutdown_computer():
"""Shutdown the computer with confirmation"""
print("Are you sure you want to shutdown? Say 'yes' to confirm or 'no' to cancel.")
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
audio = r.listen(source, timeout=5)
try:
confirmation = r.recognize_google(audio).lower()
print(f"You said: {confirmation}")
if "yes" in confirmation:
print("Shutting down in 3 seconds...")
time.sleep(3)
system = platform.system()
if system == "Windows":
os.system("shutdown /s /t 0")
elif system in ["Linux", "Darwin"]:
os.system("sudo shutdown -h now")
else:
print("Shutdown cancelled.")
except (sr.UnknownValueError, sr.RequestError, sr.WaitTimeoutError):
print("Confirmation not understood. Shutdown cancelled for safety.")
def main():
"""Main function with enhanced safety features"""
r = sr.Recognizer()
print("Enhanced Voice Shutdown Script")
print("Say 'shutdown my computer' to initiate shutdown")
print("" * 40)
while True:
try:
with sr.Microphone() as source:
print("Listening...")
r.adjust_for_ambient_noise(source)
audio = r.listen(source, timeout=10)
text = r.recognize_google(audio).lower()
print(f"Command: {text}")
if "shutdown" in text and ("computer" in text or "pc" in text):
shutdown_computer()
elif "exit" in text or "quit" in text:
print("Goodbye!")
break
except sr.UnknownValueError:
print("Speech not recognized. Try again.")
except sr.RequestError as e:
print(f"Speech service error: {e}")
except sr.WaitTimeoutError:
print("No speech detected. Continuing to listen...")
except KeyboardInterrupt:
print("\nProgram stopped.")
break
if __name__ == "__main__":
main()
Key Features
| Feature | Description | Benefit |
|---|---|---|
| Voice Recognition | Converts speech to text using Google API | Handsfree operation |
| CrossPlatform | Works on Windows, Linux, and macOS | Universal compatibility |
| Safety Confirmation | Asks for verbal confirmation | Prevents accidental shutdowns |
| Error Handling | Handles speech recognition failures | Robust operation |
Troubleshooting Tips
Microphone Issues: Ensure your microphone is properly connected and set as the default input device
Internet Connection: Google's speech recognition requires an active internet connection
PyAudio Installation: On Linux, you may need to install
portaudiofirst:sudo apt-get install portaudio19-devPermissions: On Linux/macOS, shutdown commands may require sudo privileges
Conclusion
You now have a functional Python script that can shutdown your computer using voice commands. The enhanced version includes safety features like confirmation prompts and crossplatform compatibility. This script demonstrates the power of combining speech recognition with system automation, opening up possibilities for creating more sophisticated voicecontrolled applications.
