1# ctypes module to load windows library
2import ctypes
3# speech recognition module
4import speech_recognition as sr
5
6# obtain audio from the microphone
7r = sr.Recognizer()
8with sr.Microphone() as source:
9 print("Say something!")
10 audio = r.listen(source)
11
12# recognize speech using Google Speech Recognition
13try:
14 # Here we are using default API which comes with the speech recognition module and is in built
15 # If you want to use your own API key please use this code `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
16 # instead of `r.recognize_google(audio)`
17 cmd=r.recognize_google(audio)
18 # handle the exceptions
19except sr.UnknownValueError:
20 print("Google Speech Recognition could not understand audio")
21except sr.RequestError as e:
22 print("Could not request results from Google Speech Recognition service; {0}".format(e))
23
24# Match and compare the pattern of the voice command. You can change it yours.
25if cmd=="lock my PC":
26 # Load and execute the command to lock the PC. This function is available in default library (user32.dll) of windows
27 ctypes.windll.user32.LockWorkStation()