簡體   English   中英

程序運行時,如果按Enter鍵如何停止音樂?

[英]How to stop music if Enter key is pressed anytime the program is running?

我希望我的程序執行以下操作:

該程序運行時:
如果按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()部分要求的,然后才能繼續。

但是,即使我按任意鍵代碼的那部分都不在乎,程序也不會陷入while循環中嗎?

winsound.SND_NOWAIT的鏈接文檔指出:

注意:現代Windows平台不支持此標志。

除此之外,我認為您不了解getch()工作原理。 這是其文檔的鏈接:

https://msdn.microsoft.com/en-us/library/078sfkak

這是一個名為kbhit()的相關kbhit() msvcrt也包含,我在下面使用):

https://msdn.microsoft.com/en-us/library/58w7c94c.aspx

當按下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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM