Stop pysttx3 in between while speaking using hotkey

I am making a Jarvis like automation bot I have written half code. But I want stop it (pysttx3) from speaking if press a trigger key. Main problem comes here:

 try:
                speak('Searching wikipedia...')
                query = query.replace("wikipedia", "")
                results = wikipedia.summary(query, sentences=2)
                speak("According to wikipedia") 
                print(results)
                while True:
                    if keyboard.is_pressed("esc"):
                        break
                    else:
                        speak(results)

                                               
             except:
                 speak("Query not available on wikipedia. Please try something else")
                 print("Query not available on wikipedia. Please try something else")

Here it does not stop if I press escape button.

Here's my whole code.

import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import keyboard  # using module keyboard


engine = pyttsx3.init('sapi5')
voices = engine.setProperty
#print(voices)

engine.getProperty('voice')
def speak(audio):
    engine.say(audio)
    engine.runAndWait()

def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour == 0 and hour < 12:
        speak("Good Morning!")
    elif hour >= 12 and hour < 18:
        speak("Good Afternoon!")
    else:
        speak("Good Evening!")
    speak("I am Ultron Sir. Please tell me how may i help you")



def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening.....")
        r.pause_threshold = 1
        r.energy_threshold = 300
        audio = r.listen(source)

    try:
        print("Recognizing...")
        query = r.recognize_google(audio, language = 'en-in')
        print(f"User said:  ",query)

    except Exception as e:

        print("Sorry sir, Couldn't recognize, please say again ...")
        return "None"
    return query


if __name__ == "__main__":
    wishMe()
    while True:
        
        query = takeCommand().lower()


        if 'wikipedia' in query:
            

             try:
                speak('Searching wikipedia...')
                query = query.replace("wikipedia", "")
                results = wikipedia.summary(query, sentences=2)
                speak("According to wikipedia") 
                print(results)
                while True:
                    if keyboard.is_pressed("esc"):
                        break
                    else:
                        speak(results)

                                               
             except:
                 speak("Query not available on wikipedia. Please try something else")
                 print("Query not available on wikipedia. Please try something else")


        elif 'open youtube' in query:
            webbrowser.open('youtube.com')

        elif 'open google' in query:
            webbrowser.open('google.com')

        elif '.com' in query:
            webbrowser.open(query)

        elif '.org' in query:
            webbrowser.open(query)

        elif 'the time' in query:
            strtime = datetime.datetime.now().strftime("%H:%M:%S")
            print(strtime)
            speak(strtime)

        elif 'open code' in query:
            codepath = "C:\\Program Files\\JetBrains\\PyCharm Community Edition 2019.2\\bin\\pycharm64.exe"
            os.startfile(codepath)

        elif 'exit ' in query:
            print("Thank You Sir.")
            speak("Thank you sir.")
            break
           

        elif 'who are you' in query:
            speak("I am Ultron, created by Mr. SD THE CODER and my mission is to serve mankind")


I would be really thankful to you if you help me.



Read more here: https://stackoverflow.com/questions/64952247/stop-pysttx3-in-between-while-speaking-using-hotkey

Content Attribution

This content was originally published by Sdthecoder at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: