首页 > 解决方案 > 如何使用 winsound 阻止声音堆叠在一起?(Python 和 tkinter)

问题描述

我正在尝试使用 tkinter 在 python 中创建一个简单的音板。我的目标是只有一个按钮,在本例中名为“bruh”,每次单击该按钮时,它都会播放“bruh.wav”声音。

到目前为止它似乎工作,但是如果我要反复按下按钮,声音会堆叠在一起,就好像它是一个队列一样。我该如何做到这一点,以便每次按下按钮都会取消任何声音播放并只播放 wav 文件的开头?

我已经阅读了 winsound 模块,“PURGE”命令似乎很有趣,但我不确定如何实现它,我只是一个初学者,对不起!

from tkinter import *

root = Tk()

def leftClick(event):
    import winsound
    winsound.PlaySound("realbruh.wav", winsound.SND_FILENAME)



frame = Frame(root, width=600, height=600)

bruhButton = Button(root, text="bruh")
bruhButton.bind("<Button-1>", leftClick)
bruhButton.pack()

root.mainloop()

即:如果我要向按钮发送垃圾邮件,“bruh”声音会一个接一个地播放,直到达到我单击按钮的次数。我怎么做才能让他们互相打扰,并且没有排队的事情?

标签: pythonbuttonaudiotkinterwinsound

解决方案


如果你只需要声音并且可以使用 pygame 模块,那么试试我的方法。

如果您没有 pygame 模块,使用pip install pygame. 我将 pygame 模块用于我的 tkinter 项目中的所有音效,并且效果很好。

这是我的做法:

from tkinter import *
import pygame

pygame.mixer.init()  # initialise `init()` for mixer of pygame. 
sound = pygame.mixer.Sound("bruh.wav")  # Load the sound.

root = Tk()

def leftClick(event):
    sound.stop()  # Stop the ongoing sound effect.
    sound.play()  # Play it again from start.

frame = Frame(root, width=600, height=600)

bruhButton = Button(root, text="bruh")
bruhButton.bind("<Button-1>", leftClick)
bruhButton.pack()

root.mainloop()

推荐阅读