One way to achieve this is to run the while loop on a different thread and have it keep track of the variable on the main thread. However it is necessary to kill the while thread when you wish to end the program.
import time
import winsound
import threading
class Player():
def __init__(self, **kwargs):
# Shared Variable.
self.alarm_status = True
self.thread_kill = False
def start_sound(self):
while True and not self.thread_kill:
# Do somthing only if flag is true
if self.alarm_status == True:
winsound.PlaySound("alarm.wav", winsound.SND_FILENAME)
def stop_sound(self):
# Update the variable to stop the sound
self.alarm_status = False
#Function to run your start_alarm on a different thread
def start_thread(self):
#Set Alarm_Status to true so that the thread plays the sound
self.alarm_status = True
t1 = threading.Thread(target=self.start_sound)
t1.start()
def run(self):
while True:
user_in = str(raw_input('q: to quit,p: to play,s: to Stop\n'))
if user_in == "q":
#Signal the thread to end. Else we ll be stuck in for infinite time.
self.thread_kill = True
break
elif user_in == "p":
self.start_thread()
elif user_in == "s":
self.stop_sound()
else:
print("Incorrect Key")
if __name__ == '__main__':
Player().run()
paused = Falseto control it.