问题
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:
# https://docs.python.org/2/library/winsound.html
from msvcrt import getch
import winsound
while True:
key = ord(getch())
if key == 13:
winsound.PlaySound(None, winsound.SND_NOWAIT)
winsound.PlaySound("SystemAsterisk", winsound.SND_ALIAS)
winsound.PlaySound("SystemExclamation", winsound.SND_ALIAS)
winsound.PlaySound("SystemExit", winsound.SND_ALIAS)
winsound.PlaySound("SystemHand", winsound.SND_ALIAS)
winsound.PlaySound("SystemQuestion", winsound.SND_ALIAS)
winsound.MessageBeep()
winsound.PlaySound('C:/Users/Admin/My Documents/tone.wav', winsound.SND_FILENAME)
winsound.PlaySound("SystemAsterisk", winsound.SND_ALIAS)
In the documentation (see link in the first line of my code), I am unsure weather winsound.SND_NOWAIT
can be used like this: winsound.SND_NOWAIT()
, or like how I tried to use it in my code under the if
statement, or if both statements produce the same effect.
It is my understanding that the program will never get to play the sound files until after I press the Enter
button, as the getch()
part requires before continuing.
However, even if that part of the code does not care when I press anything, wouldn't the program get stuck in the while
loop?
回答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
class StopPlaying(Exception): pass # custom exception
def check_keyboard():
while kbhit():
ch = getch()
if ch in '\x00\xe0': # arrow or function key prefix?
ch = getch() # second call returns the actual key code
if ord(ch) == 13: # <Enter> key?
raise StopPlaying
def play_sound(name, flags=winsound.SND_ALIAS):
winsound.PlaySound(name, flags)
check_keyboard()
try:
while True:
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')
来源:https://stackoverflow.com/questions/45113705/how-to-stop-music-if-enter-key-is-pressed-anytime-the-program-is-running