Filip GG
Filip GG

Reputation: 31

Python wakeup word for AI assistant

I have a voice assistant in python and can't add a wake word. When I execute the code it just keeps listening until I stop talkin then it shuts off I need to make it keep listening for a wake word and when it hears the wake word to listen for I command.

import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
import requests
from bs4 import BeautifulSoup
from selenium import webdriver

listener = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
rn = sr.Recognizer()


def talk(text):
    engine.say(text)
    engine.runAndWait()


def take_command():
    try:
        with sr.Microphone() as source:
            print('listening...')
            rn.adjust_for_ambient_noise(source)
            voice = rn.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            if 'alexa' in command:
                command = command.replace('alexa', '')
                print(command)
    except:
        pass
    return command


def run_alexa():
    command = take_command()
    print(command)
    if 'play' in command:
        song = command.replace('play', '')
        talk('playing ' + song)
        pywhatkit.playonyt(song)
    elif 'time' in command:
        time = datetime.datetime.now().strftime('%I:%M %p')
        print(time)
        talk('Current time is ' + time)
    else:
        talk('Please say the command again.')


while True:
    run_alexa()

Upvotes: 1

Views: 2295

Answers (1)

Naman Doctor
Naman Doctor

Reputation: 182

You can try doing the following:

wake_word = "your wake word"

while True:
    print("Listening")
    text = take_command()

    if text.count(wake_word) > 0:
        talk("I am ready")
        run_alexa

Upvotes: 0

Related Questions