Open Menu dzosoft
Close Menu dzosoft

   ALL ABOUT COMPUTER SCIENCE AND TECHNOLOGY


                             










 
 
 

Lock PC with voice command using Python

 
 
Lock PC with voice command using Python
 
In this tutorial, I’ll show you how to Lock PC with voice command using Python and the Google Speech API.
first of all, we need to setup environment to write and test the code.
 

Setup Environment

 
 

Install Python

Install SpeechRecognition Python module
You can install any Python module using pip command. Open command prompt
and execute this command to install the SpeechRecognition module.
pip install SpeechRecognition

 

Sample Source Code

 
This is the Python source that will Lock the PC with voice command.
Also, the source code contains the explanation.
# ctypes module to load windows library
import ctypes
# speech recognition module
import speech_recognition as sr

# obtain audio from the microphone r = sr.Recognizer() with sr.Microphone() as source: print("Say something!") audio = r.listen(source)
# recognize speech using Google Speech Recognition try: # Here we are using default API which comes with the speech recognition module and is in built # If you want to use your own API key please use this code `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")` # instead of `r.recognize_google(audio)` cmd=r.recognize_google(audio) # handle the exceptions except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e))
# Match and compare the pattern of the voice command. You can change it yours. if cmd=="lock my PC": # Load and execute the command to lock the PC. This function is available in default library (user32.dll) of windows ctypes.windll.user32.LockWorkStation()

Execute the command through the command line or clicking on the file. You can execute the script using
command line using the following command:
python lockpc.py

While the script is in execution, speak this command i.e. “lock my PC” if you use the
same keyword as mentioned in the code above.
Make sure you are connected to the internet and your PC mic is working properly.
Your PC will be locked once the script recognized your voice.
There might be a delay of few seconds depending on the internet speed and response of the Google Speech API.


It might also interest you


How to install Python on Windows

How to write your first Python program

How to connect MySQL database using Connector/Python

How to draw shapes with python

How to create read and write to a file in python

How to create your own personal assistant using ChatGPT and Python

How to create and initialize a Python dictionary


Leave comment
          

Save nickname and email in this browser for the next time.



Loading...