How do I get my python virtual assistant to only listen once it hears a wake word?

Question:

I have a python virtual assistant that is always listening for commands. How can I make it so she only starts listening to commands once she hears the wake word such as Alexa, or in this case Anna. If you have any tips or answers they will be greatly appreciated. Thank you!

import speech_recognition as sr
import pyttsx3

tts = pyttsx3.init()

voices = tts.getProperty('voices')
tts.setProperty('voice', voices[1].id)

def takeCommand():

    r = sr.Recognizer()

    with sr.Microphone() as source:
        print('Listening...')

        r.pause_threshold = 0.5
        audio = r.listen(source)
        
        try:
            print("Recognizing")
            
            Query = r.recognize_google(audio, language='en-us')
            print("the command is printed=", Query)
            
        except Exception as e:
            print(e)
            print("Say that again")
            return "None"
        
        return Query

def Take_query():

    while(True):

        query = takeCommand().lower()
        if "Hello" in query:
            tts.say('Hello')
            tts.runAndWait()
            continue

        elif "How are you" in query:
            tts.say('I am good')
            tts.runAndWait()
            continue

if __name__ == '__main__':
    Take_query()
Asked By: Cason Wilson

||

Answers:

Anna will always listen, so you have 2 choices

  1. force the program to ignore any query without Anna

so the program will ignore anything doesn’t start with Anna

def takeCommand():

    r = sr.Recognizer()

    with sr.Microphone() as source:
        print('Listening...')

        r.pause_threshold = 0.5
        audio = r.listen(source)
        
        try:
            print("Recognizing")
            
            Query = r.recognize_google(audio, language='en-us')
            print("the command is printed=", Query)
            
            
        except Exception as e:
            print(e)
            print("Say that again")
            return "None"
        if Query.startswith("Anna"):
            return Query
        else:
            return "None"
  1. Nested recognition

this is might be better for you, just nest the recognition, first recognize Anna then and only then the command

hope that helps you

Answered By: user18932371
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.