If boolean is false for 1 second, break from loop

I tried using threading, but I couldn’t break from the loop from another thread. I’m trying to see if talking is false for 1 second, and if it is break from the while loop. Pretty simple I guess, here is my code:

trange = 50;
talking = False;

import pvcobra
from pvrecorder import PvRecorder;

cobra = pvcobra.create(access_key='imnottellingyou')

recorder = PvRecorder(512, device_index=-1)
recorder.start()
def get_next_audio_frame():
    return recorder.read();
while True:
    audio_frame = get_next_audio_frame()
    voice_probability = cobra.process(audio_frame)
    if voice_probability > trange / 100:
        print("talking - confidence is above " + str(trange) + "%, at " + str(voice_probability * 100) + "%");
        talking = True;
    else:
        print("silent - confidence is below " + str(trange) + "%, at " + str(voice_probability * 100) + "%");
        talking = False;

You are not showing all the code.

Where is the code of the thread that looks at the talking variable?
Indeed where is the talking variable defined initially?

I tried using threading, but it didn’t work and it was a bit too complicated because I’m going to add this to a different script. I was asking if there is a different way to do it. And the talking variable is defined in the loop, but I will make it be defined initially at the beginning of the code to be false to make it function better and make it less confusing.

A threaded version should work.
If you have a threaded version that you cannot get going I can review and help.
I would suggest that you remember time that the talking starts and then its easy for another thread to see if its been 1.0 seconds.
(Assuming I have understood what you are doing).

Instead of simply setting a boolean, use a variable to remember the last time that the talking stopped. When you detect that there is talking, set the variable to None or some other dummy value. When you detect that there is no talking, check the system time again. If the variable is the dummy value, then the talking has just stopped, so record the time. Otherwise, you can trivially see if the desired amount of time has passed.

1 Like