Python 如果在程序运行时按Enter键,如何停止音乐?

Python 如果在程序运行时按Enter键,如何停止音乐?,python,windows,python-2.7,audio,winsound,Python,Windows,Python 2.7,Audio,Winsound,我希望我的程序按照以下思路执行: 此程序运行时: 如果按下Enter键,则停止播放当前音乐文件。 这是我的密码: # 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_

我希望我的程序按照以下思路执行:

此程序运行时:
如果按下
Enter
键,则停止播放当前音乐文件。


这是我的密码:

# 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)

在文档中(请参阅我代码第一行中的链接),我不确定winsound.SND_NOWAIT是否可以这样使用:
winsound.SND_NOWAIT()
,或者我如何尝试在
if
语句下的代码中使用它,或者两个语句是否产生相同的效果

据我所知,在我按下
Enter
按钮之前,程序将无法播放声音文件,这是
getch()
部分在继续之前所要求的


然而,即使当我按下任何键时,代码的这一部分并不重要,程序在循环时不会陷入
中吗?

winsound.SND_NOWAIT的链接文档声明:

注意:现代Windows平台不支持此标志

除此之外,我认为您不了解
getch()
的工作原理。以下是其文档的链接:

下面是另一个相关的名为
kbhit()
(它
msvcrt
也包含,我在下面使用):

按下Enter键时,以下命令将停止循环(以及程序,因为这是其中的唯一内容)。请注意,它不会中断任何已经播放的声音,因为
winsound
没有提供这样做的方法,但它会停止播放任何其他声音

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')
从msvcrt导入getch,kbhit
导入winsound
类StopPlaying(异常):通过#自定义异常
def check_键盘():
而kbhit():
ch=getch()
如果输入“\x00\xe0”:#箭头或函数键前缀?
ch=getch()#第二个调用返回实际的键代码
如果ord(ch)=13:#键?
加高
def播放声音(名称、标志=winsound.SND_别名):
winsound.PlaySound(名称、标志)
检查键盘()
尝试:
尽管如此:
播放声音(“系统星号”)
播放声音(“系统感叹号”)
播放声音(“系统退出”)
播放声音(“系统手”)
播放声音(“系统问题”)
winsound.MessageBeep()
播放声音('C:/Users/Admin/My Documents/tone.wav',winsound.SND_文件名)
播放声音(“系统星号”)
除铺设外:
打印('按Enter键')