I have a code that will play an alarm then when I press h it should stop working here's the code:
import winsound
from threading import Thread
import keyboard
import sys
alarm_flag = True
def alarm():
global alarm_flag
while alarm_flag:
winsound.PlaySound("C:\\windows\\media\\Alarm01.wav", winsound.SND_FILENAME)
def stop_alarm():
global alarm_flag
while True:
if keyboard.is_pressed("h"):
alarm_flag = False
alarm_thread = Thread(target=alarm)
stop_alarm_thread = Thread(target=stop_alarm)
alarm_thread.start()
stop_alarm_thread.start()
when I press "h" it will wait for the winsound to end (it's a 5 second alarm) and then exits the program I want it to kill everything when I press "h" so the winsound will stop at the middle, first or end no matter what I also tried with sys.exit()
but it's not working
I found a way to do it with pygame instead of winsound (thanks to chatGPT) here's how :
and the whole code will look like this :