pythonpython-multithreadingalarmwinsound

how to kill winsound task after an if condition


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


Solution

  • I found a way to do it with pygame instead of winsound (thanks to chatGPT) here's how :

        pygame.mixer.init()
        pygame.mixer.music.load("C:\\windows\\media\\Alarm01.wav")
        pygame.mixer.music.play(-1)  # -1 for looping
    

    and the whole code will look like this :

    import pygame
    from threading import Thread
    import keyboard
    import sys
    import time
    
    alarm_flag = True
    
    
    def alarm():
        global alarm_flag
        pygame.mixer.init()
        pygame.mixer.music.load("C:\\windows\\media\\Alarm01.wav")
        pygame.mixer.music.play(-1)  # -1 for looping
    
        while alarm_flag:
            time.sleep(1)
    
    
    def stop_alarm():
        global alarm_flag
        while True:
            if keyboard.is_pressed("Esc"):
                alarm_flag = False
                pygame.mixer.music.stop()
                sys.exit()
    
    
    alarm_thread = Thread(target=alarm)
    stop_alarm_thread = Thread(target=stop_alarm)
    
    alarm_thread.start()
    stop_alarm_thread.start()