Open In App

Python Script to Shutdown your PC using Voice Commands

Improve
Improve
Like Article
Like
Save
Share
Report

Yes, it is possible with the help of terminal and some modules in Python through which one can shut down a PC by just using voice commands

Required Modules:

  • OS module: It is an in-built module in python that provides function for interacting with the operating system.
  • Speech Recognition module: It is an external module in python whose functionality depends on the voice commands of the user.
  • Pyttsx3 module: it is a text-to-speech conversion library in Python.

Installation:

pip install SpeechRecognition
pip install pyttsx3

Role of Terminal:

In terminal there are many tags for the shutdown command, however we will use the /s tag with it to shut down the system.

Below are the steps to create a program to shut doe=wn PC using Voice Commands:

Step 1: Create a class Gfg and then create its methods, create takeCommands() method to take commands as input.

Python3




import SpeechRecognition as sr
 
# Create class
class Gfg:
     
    # Method to take voice commands as input
    def takeCommands(self):
         
        # Using Recognizer and Microphone Method for input voice commands
        r = sr.Recognizer()
        with sr.Microphone() as source:
            print('Listening')
             
            # Number pf seconds of non-speaking audio before
            # a phrase is considered complete
            r.pause_threshold = 0.7
            audio = r.listen(source)
             
            # Voice input is identified
            try:
                 
                # Listening voice commands in indian english
                print("Recognizing")
                Query = r.recognize_google(audio, language='en-in')
                 
                # Displaying the voice command
                print("the query is printed='", Query, "'")
                 
            except Exception as e:
                 
                # Displaying exception
                print(e) 
                print("Say that again sir")
                return "None"
        return Query


Step 2: Create a Speak() method so that the computer can communicate with the user.

Python3




# Method for voice output
def Speak(self, audio):
   
    # Constructor call for pyttsx3.init()
    engine = pyttsx3.init('sapi5')
     
    # Setting voice type and id
    voices = engine.getProperty('voices')
    engine.setProperty('voice', voices[1].id)
    engine.say(audio)
    engine.runAndWait()


Step 3: Now create the quitSelf() to shut down the computer. 

Python3




# Method to self shut down system
def quitSelf(self):
    self.Speak("do u want to switch off the computer sir")
     
    # Input voice command
    take = self.takeCommand()
    choice = take
    if choice == 'yes':
         
        # Shutting down
        print("Shutting down the computer")
        self.Speak("Shutting the computer")
        os.system("shutdown /s /t 30")
    if choice == 'no':
         
        # Idle
        print("Thank u sir")
        self.Speak("Thank u sir")


 
 

Step 4: Now in the driver code create a Gfg object and call the quitSelf() method.

Python3




# Driver code
if __name__ == '__main__':
     
    # Creating gfg object
    Maam = Gfg()
     
    # Calling the method to self shut down
    Maam.quitSelf()


Below is the complete program to shut down a PC using voice commands:

Python




# Importing required modules
import os
import pyttsx3
import speech_recognition as sr
 
 
 
# Creating class
class Gfg:
     
    # Method to take choice commands as input
    def takeCommands(self):
         
          # Using Recognizer and Microphone Method for input voice commands
          r = sr.Recognizer()
          with sr.Microphone() as source:
              print('Listening')
 
              # Number pf seconds of non-speaking audio before
              # a phrase is considered complete
              r.pause_threshold = 0.7
              audio = r.listen(source)
 
              # Voice input is identified
              try:
 
                  # Listening voice commands in indian english
                  print("Recognizing")
                  Query = r.recognize_google(audio, language='en-in')
 
                  # Displaying the voice command
                  print("the query is printed='", Query, "'")
 
              except Exception as e:
 
                  # Displaying exception
                  print(e) 
                  # Handling exception
                  print("Say that again sir")
                  return "None"
          return Query
 
     
    # Method for voice output
    def Speak(self, audio):
   
          # Constructor call for pyttsx3.init()
          engine = pyttsx3.init('sapi5')
 
          # Setting voice type and id
          voices = engine.getProperty('voices')
          engine.setProperty('voice', voices[1].id)
          engine.say(audio)
          engine.runAndWait()
 
     
    # Method to self shut down system
    def quitSelf(self):
        self.Speak("do u want to switch off the computer sir")
 
        # Input voice command
        take = self.takeCommands()
        choice = take
        if choice == 'yes':
 
            # Shutting down
            print("Shutting down the computer")
            self.Speak("Shutting the computer")
            os.system("shutdown /s /t 30")
        if choice == 'no':
 
            # Idle
            print("Thank u sir")
            self.Speak("Thank u sir")
 
             
 
# Driver code           
if __name__ == '__main__':
    Maam = Gfg()
    Maam.quitSelf()


Output:

Code Explanation:

  1. The code begins by importing the pyttsx3 module.
  2. This module provides functions for working with TTS (Text-To-Speech) engines.
  3. Next, the code creates an instance of the pyttsx3.init() function, passing in the name of the TTS engine to be used (in this case, “sapi5”).
  4. Once the engine has been initialized, the Speak() method is called.
  5. This method takes two arguments: a string containing the text to be spoken and an audio file object.
  6. The audio file object is used to provide input to the TTS engine.
  7. The Speak() method begins by calling pyttsx3.init() again, but this time with a different argument: a pathname specifying where to find the text files that will be used by the TTS engine.
  8. The text files must be located in a directory named “data” on your computer; otherwise, PyTTS will not be able to locate them and errors will occur during execution of the code.
  9. Next, a new instance of pyttsx3.TextStream is created and initialized with data from one of the text files specified in data/ .
  10. The TextStream object contains information about each individual
  11. The code first imports the necessary packages.
  12. It then creates an instance of the pyttsx3 library, which is used to generate voice output.
  13. Next, a instance of the pyttsx3.init() function is called, which specifies the desired audio engine to be used (in this case, it is using the ‘sapi5’ audio engine).
  14. Once the necessary packages have been imported and initialized, the Speak() method will be called.
  15. This method will require two arguments: first, an audio file name (in this case, ‘test_audio.mp3’), and second, a pointer to an object that will contain all of the relevant information about how to produce voice output from that audio file
  16. The code begins with a few lines of input that ask the user for two command-line options.
  17. The first option is to shut down the computer, and the second option is to idle (keep the computer running but inactive).
  18. The code then starts to run.
  19. First, it asks the user for a choice: should it shut down or idle?
  20. If the user chooses to idle, then the code prints out “Thank you sir” and goes on to execute an os.system() call that will shutdown the computer in 30 seconds.
  21. If instead the user chooses to shut down, then the code asks for another choice: should it do a quick shutdown or a full shutdown?
  22. If they choose quick shutdown, then os.system() will only shut down parts of the system – not completely shutting down everything like a full shutdown would.
  23. If they choose full shutdown, then os.system() will actually turn off all power to the computer and wait until it’s turned back on before continuing execution.
  24. Finally, if either choice was chosen incorrectly (the user didn’t enter any commands), an error message is printed out and control returns back to where it was originally called from within this script – in this case, from main().
  25. The code first checks if the user has chosen to take a command by checking the choice variable.
  26. If the choice is ‘yes’, it will then shut down the computer.
  27. If the choice is ‘no’, it will instead keep the computer idle.


Last Updated : 20 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads