How To Stop Music If Enter Key Is Pressed Anytime The Program Is Running?
I want my program do something along the lines of: while this program is running: if the Enter key is pressed, stop the current music file playing. Here is my code: # htt
Solution 1:
The linked documentation for winsound.SND_NOWAIT
states that:
Note: This flag is not supported on modern Windows platforms.
Besides that I don't think you understand how getch()
works. Here's a link to its documentation:
https://msdn.microsoft.com/en-us/library/078sfkak
And here's another for a related one named kbhit()
(which msvcrt
also contains and I use below):
https://msdn.microsoft.com/en-us/library/58w7c94c.aspx
The following will stop the loop (and the program, since that's the only thing in it) when the Enter key is pressed. Note that it doesn't interrupt any single sound already playing because winsound
doesn't provide a way to do that, but it will stop any further ones from being played.
from msvcrt import getch, kbhit
import winsound
classStopPlaying(Exception): pass# custom exceptiondefcheck_keyboard():
while kbhit():
ch = getch()
if ch in'\x00\xe0': # arrow or function key prefix?
ch = getch() # second call returns the actual key codeiford(ch) == 13: # <Enter> key?raise StopPlaying
defplay_sound(name, flags=winsound.SND_ALIAS):
winsound.PlaySound(name, flags)
check_keyboard()
try:
whileTrue:
play_sound("SystemAsterisk")
play_sound("SystemExclamation")
play_sound("SystemExit")
play_sound("SystemHand")
play_sound("SystemQuestion")
winsound.MessageBeep()
play_sound('C:/Users/Admin/My Documents/tone.wav', winsound.SND_FILENAME)
play_sound("SystemAsterisk")
except StopPlaying:
print('Enter key pressed')
Post a Comment for "How To Stop Music If Enter Key Is Pressed Anytime The Program Is Running?"