Python如何给让电脑蜂鸣器哼歌加一个暂停键,需要暂停或者结束播放的那个命令
这是游戏结束在屏幕窗口中显示消息的功能
def gameover_display_message(rbtn_image, gmo_image):
rbtn_rect = rbtn_image.get_rect()
rbtn_rect.centerx = width_screen / 2
rbtn_rect.top = height_screen * 0.52
gmo_rect = gmo_image.get_rect()
gmo_rect.centerx = width_screen / 2
gmo_rect.centery = height_screen * 0.35
screen_layout_display.blit(rbtn_image, rbtn_rect)
screen_layout_display.blit(gmo_image, gmo_rect)
要实现在使用Python控制电脑蜂鸣器哼歌时,暂停或结束播放音乐需要使用winsound
模块和多线程。以下是具体的解决方案:
winsound
模块和threading
模块:import winsound
import threading
def play_music():
# 播放音乐的代码
...
# 循环播放音乐,检测标志位
while True:
if pause_flag:
# 暂停播放
winsound.PlaySound(None, winsound.SND_PURGE)
while pause_flag:
# 检测暂停标志位是否恢复为False
pass
# 继续播放
winsound.PlaySound(music_file, winsound.SND_ASYNC)
if stop_flag:
# 停止播放
winsound.PlaySound(None, winsound.SND_PURGE)
break
pause_flag = False
stop_flag = False
def pause_music():
global pause_flag
pause_flag = not pause_flag
def stop_music():
global stop_flag
stop_flag = True
pause_button = Button(root, text='暂停', font=('隶书', 15), command=pause_music)
pause_button.grid(row=3, column=2)
stop_button = Button(root, text='停止', font=('隶书', 15), command=stop_music)
stop_button.grid(row=3, column=3)
这样就可以通过点击暂停按钮和停止按钮来控制音乐的暂停或结束播放了。