pythonaudiotkinterwinsound

Playing a sound continuously with winsound and stop it with a button click


I'm trying to work with winsound in Python 3. To start the sound I do it like this:

play = lambda: PlaySound('Sound.wav', SND_FILENAME)
play()

This only plays the sound one time, but I want to loop it. Is there a built in function to loop the sound?

The next step: In tkinter I have a button with a command:

button3 = Button(root, text="Stop Alarm", fg="Red", bg="Black", command=stopAlarm)

The given command should stop the already looping sound from playing. This is the function:

def stopAlarm():
    #stop the alarm

So in short I want to loop the sound, and be able to stop the sound any idea how I can accomplish this?


Solution

  • To play a sound continuously with winsound, you can combine the SND_FILENAME, SND_LOOP, SND_ASYNC constants with a bitwise OR |: SND_FILENAME|SND_LOOP|SND_ASYNC.

    And to stop the sound, you can just pass None as the first argument to PlaySound.

    import tkinter as tk
    from winsound import PlaySound, SND_FILENAME, SND_LOOP, SND_ASYNC
    
    
    class App:
    
        def __init__(self, master):
            frame = tk.Frame(master)
            frame.pack()
            self.button = tk.Button(frame, text='play', command=self.play_sound)
            self.button.pack(side=tk.LEFT)
            self.button2 = tk.Button(frame, text='stop', command=self.stop_sound)
            self.button2.pack(side=tk.LEFT)
    
        def play_sound(self):
            PlaySound('Sound.wav', SND_FILENAME|SND_LOOP|SND_ASYNC)
    
        def stop_sound(self):
            PlaySound(None, SND_FILENAME)
    
    root = tk.Tk()
    app = App(root)
    root.mainloop()