python - 如何使用 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”声音会一个接一个地播放,直到达到我单击按钮的次数。我怎么做才能让他们互相打扰,并且没有排队的事情?
解决方案
如果你只需要声音并且可以使用 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()
推荐阅读
- sql - 如何按特定顺序分组?
- excel - 从特定工作表中删除特定列会导致“未定义子或函数”编译错误
- java - 每当在任何其他服务中自动装配时,如何使 POJO 在 setter 中返回修改后的值?
- python - KERAS: AttributeError: 'BatchDataset' object has no attribute 'ndim' ,Tensorflow 图像分割演示不适用于我的 anaconda
- java - 服务在 android 8 (oreo) 下意外停止
- python - Matplotlib Axes3D 比率 Savefig
- angular - 使用 Angular 6 和 rdflib 0.19.0 找不到模块“算法/RSASSA-PKCS1-v1_5”
- javascript - Gremlin,javascript:从哪里导入函数“valueMap()”?
- python - 使用python将文件从文件夹导入数组
- vb.net - VB.NET 中的 WebService 调用问题