Search code examples
pythonpython-3.xloopspyttsx3

How to let pyttsx3 only listen when a command is given?


I would like pyttsx3 to only listen when a click some sort of button or speak some sort of hotword otherwise it should stay quiet and keep waiting for my command.

My code runs in a loop like shown below:

    if __name__ == "__main__":  # main program
    wish()
    while True:
        # if 1:

        query = takecommand().lower()

        # logic building for tasks

        if "open notepad" in query:
            npath = "C:\\Windows\\system32\\notepad.exe"
            os.startfile(npath)

        elif 'hi' in query or 'hello' in query:
            speak('Hello sir, how may I help you?')
time.sleep(3)

and so on...


Solution

  • How About this:

    Wake = "Hey Robot" #here you can use whatever word you want
    while True: 
    
        text = get_audio().lower()# this takes the audio. Change this for the name of your audio function
    
        if text.count(Wake) > 0:
            speak("I am On.")
            text = get_audio().lower()#This make it say I am on when it is activated. And then start listening
        #Erase the .lower() if your talk function has it implemented
        hi_words = ["hello", "hi",]
    
        for phrase in hi_words:
            if phrase in text:
                speak("Hello sir, how may I help you")
    

    This will make the program activate when you say the wake word. Then it will wait for a command, Afterwards it will go to sleep and wait till you say the wake word again