Home > Enterprise >  PySimpleGUI not looping as it should
PySimpleGUI not looping as it should

Time:07-17

I know it is a simple fix, but it's hard to find your own mistakes. I've been at it for a while and can't figure out why the window is behaving erratically. I'm trying to capture voice events with speech-recognition (no problems here), and then count how many times the words was said (no problem here). The problem, however, is that so far it is capturing the first event, and then the it stops capturing it while the window stays open and the code runs in the background. I think it must be a while loop issue, but I can't figure out what or where exactly. Thanks for your time in taking a look.

#!/usr/bin/python
import pyttsx3
import pyaudio
import speech_recognition as sr
import PySimpleGUI as sg
import sys


engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[1].id)
engine = pyttsx3.init()

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

def take_command():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source)
        print("Listening for command...")
        r.pause_threshold = 0.5
        audio = r.listen(source)
    try:
        print("Recognizing voice...")
        query = r.recognize_google(audio, language='en-US')
        print(query)
    except Exception as e:
        print(e)
        print("Unable to recognize. Try again please.")
        return "None"
    print(type(query))
    return query

if __name__ == "__main__":

    sg.set_options(background_color='#f3f6f4',element_background_color='#edeeef',text_color='black',text_element_background_color='#f3f6f4')
    layout = [[sg.Text('Hello Counter',font='Lucinda 16',size=(20,1))],
                [sg.Text(key='OUTPUT',font='Lucinda 12',text_color='green',size=(2,1),pad=(0,10)),sg.Text('Hello',font='Lucinda 14',size=(15,1),pad=(0,10))],
                [sg.Button('Count'),sg.Button('Exit',button_color=('white','#D33F49'))]]
    window = sg.Window('Hello Counter',layout,return_keyboard_events=True)

    counter = 0
    while True:
        event,values = window.read()
        if event == 'Exit' or event == sg.WIN_CLOSED:
            sys.exit()

        if event == 'Count':
            query = take_command().lower()

            if 'hello' in query:
                counter  =1
                print(counter)
                window['OUTPUT'].update(counter)
            if "stop" in query:
                speak("Ok")
                sys.exit()  

CodePudding user response:

Your while True loop requires clicking the Count button again and again as the voice recognition starts only if the GUI reports a Count button click. The code below should let your script behave as you expect it to behave. With the Count button click you enable the run of voice recognition function by setting startListening to True and call the voice recognition function from within if startListening: and you prevent freezing the GUI window by updating the PySimpleGUI text output element with a string value str(counter) instead of an integer counter value.

startListening = False

while True:
    event,values = window.read(timeout=200)
    if event == 'Exit' or event == sg.WIN_CLOSED:
        sys.exit()

    if event == 'Count':
        startListening = True

    if startListening: 
        query = take_command().lower()
        if 'hello' in query:
            counter  =1
            print(counter)
            window['OUTPUT'].update(str(counter))
        if "stop" in query:
            speak("Ok")
            sys.exit()  

CodePudding user response:

Try changing your window.read command from:

event,values = window.read()

to:

 event, values = window.read(timeout=200)

the timeout will allow the loop to run even if the user hasn't interacted with the window.

  • Related