pythonbuttonaudiotkinterwinsound

How do I stop sounds stacking on top of each other with winsound? (Python and tkinter)


I'm trying to create a simple soundboard in python using tkinter. My aim is to just have one button, in this instance titled "bruh", where every time the button is clicked, it plays the "bruh.wav" sound.

So far it seems to work, however if I was to press the button repeatedly, the sounds would stack on top of each other as if it's a queue. How do I make it so every button press cancels any sound playing and just plays the beginning of the wav file?

I've read into the winsound module, the "PURGE" commands seems of interest but I am unsure as to how to implement it, I'm only a beginner, sorry!

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

ie: If I was to spam the button, the "bruh" sound would play one after the other until it reaches the amount of times I clicked the button. How do I make it so they interrupt each other, and there is no queue thing?


Solution

  • If the sound is all you need and can use pygame module then try my method.

    If you don't have pygame module then install it with pip install pygame. I use pygame module for all the sound effects in my tkinter projects and it works fine.

    Here is how I did it:

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