0

I have the following function that is part of a stopwatch program I am writing, and It will count down from a given time but for that last 5, it will play an audio clip. Basically, the function should count down from 5 at 1 second intervals. However, the length of the time of the audio clip is added to the time interval of the program executing. So it's 1 second + the length of the audio clip. I've tried moving the time.sleep to before the if conditional, but it's still the same net gain. Is there any way to have the while loop run exactly every second, regardless if there is a sound bit being played?

def countdown(timer_count,count_type):
    counter = timer_count
    count_type = count_type
    while counter >= 0:
        COUNT_DOWN_TEXT.config(text=f"{count_type} for: {counter}")
        main.update()
        if counter == 1:
            playsound('sound/1-sec-daisy.mp3')
        elif counter == 2:
            playsound('sound/2-sec-daisy.mp3')
        elif counter == 3:
            playsound('sound/3-sec-daisy.mp3')
        elif counter == 4:
            playsound('sound/4-sec-daisy.mp3')
        elif counter == 5:
            playsound('sound/5-sec-daisy.mp3')
        time.sleep(1)
        counter -= 1
        print(counter)
    if count_type != "workout":
        count_type = "workout"
    elif count_type == "workout":
        count_type = "rest"
    return count_type
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
jon
  • 349
  • 3
  • 4
  • 20
  • Does this answer your question? [Whenever I use the "playsound" to play sound in the background the rest of my game does not load](https://stackoverflow.com/questions/54053953/whenever-i-use-the-playsound-to-play-sound-in-the-background-the-rest-of-my-ga) – Tomerikoo Oct 11 '21 at 09:37

1 Answers1

1

As the code is executing in a sequential manner i.e, play a sound and then wait for 1 second, the total would be 1 second + length of sound. If you want to ensure total is 1 second, you have two options

  1. Play the sound in a separate thread (Please check for multi threading in python)
  2. Reduce the length of sound from 1 second and then apply sleep on the remaining time
Venkat
  • 115
  • 1
  • 2
  • 8