#๐Ÿ”’ help with functions

22 messages ยท Page 1 of 1 (latest)

pliant oracle
#

hello! im struggling with stopping my function because im experimenting with voice recognition and it seems to work fine but whenever i press "q" which "stops" it from listening but it doesnt. what it does instead is, whenever it stops listening (cause i put a duration) it starts listening again. it does that over and over and over and the only way to stop it is to kill the script.

fresh marshBOT
#

@pliant oracle

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

pliant oracle
#
import speech_recognition as sr
from pynput.keyboard import KeyCode, Controller, Listener
import threading

# make a recognizer instance
r = sr.Recognizer()

# make a controller instance
keyboard = Controller()

# flag to control listening
listening = False

# function to execute commands
def execute_command(command):
    if command == "skip song":
        keyboard.press(KeyCode.from_vk(0xB0))  # next track
        keyboard.release(KeyCode.from_vk(0xB0))
    elif command == "previous song":
        keyboard.press(KeyCode.from_vk(0xB1))  # previous track
        keyboard.release(KeyCode.from_vk(0xB1))
    elif command == "stop song":
        keyboard.press(KeyCode.from_vk(0xB2))  # stop track
        keyboard.release(KeyCode.from_vk(0xB2))
    elif command == "play song":
        keyboard.press(KeyCode.from_vk(0xB3))  # play track
        keyboard.release(KeyCode.from_vk(0xB3))

# function to start listening
def start_listening():
    global listening
    # use the microphone as the audio source
    with sr.Microphone() as source:
        while listening:
            print("Listening...")
            audio = r.record(source, duration=3)  # record voice for 3 seconds
            try:
                # use google speech recognition
                command = r.recognize_google(audio)
                print(f"You said: {command}")
                execute_command(command)
            except sr.UnknownValueError:
                print("Google Speech Recognition could not understand audio")
            except sr.RequestError as e:
                print(f"Could not request results from Google Speech Recognition service; {e}")

# Function to handle key press
def on_press(key):
    global listening
    if key.char == 's':  # start listening if s is pressed
        listening = True
        start_listening()
    elif key.char == 'q':  # stop listening if q is pressed
        listening = False
#
# make a listener instance
with Listener(on_press=on_press) as listener:
    listener.join()
#

my code exceeded the limit

bleak basin
#

So what I think is happening here is that your start_listening() call in your on_press() function is blocking your listener thread

def on_press(key):
    global listening
    if key.char == 's':  # start listening if s is pressed
        listening = True
        start_listening()  # <-- this right here
    elif key.char == 'q':  # stop listening if q is pressed
        listening = False
#

So basically while a Listener is a thread object that would normally run asynchronously, but because you called a regular function from within it, it cannot continue it's normal operation until the called funtion returned.

#
def on_press(key):
    global listening
    if key.char == 's':  # start listening if s is pressed
        listening = True
        
    elif key.char == 'q':  # stop listening if q is pressed
        listening = False


# make a listener instance
with Listener(on_press=on_press) as listener:
    start_listening()
    listener.join()

try moving the call to your start_listening() function outside of your on_press().

pliant oracle
#

alright

pliant oracle
#

i tried just now, it doesnt print "Listening..." anymore for some reason

#

nevermind it was because of this blank space between

#

it does work, thats great. but theres another problem
it keeps listening over and over again

#

heres a video of the behavior im describing

bleak basin
#

What is the condition you want it to stop listening on? Because right now in your code it will only ever stop listening if the listening flag is False. The only place that can happen is in your on_press function. So it will only stop if you press q.
If you want it to stop you have to set listening to false.

pliant oracle
#

oh wait

#

nevermind

#

i got it already

#

thank you

#

!!

#

!close

fresh marshBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.