2

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?

skrx
  • 19,980
  • 5
  • 34
  • 48
Kevin.a
  • 4,094
  • 8
  • 46
  • 82

1 Answers1

3

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()
skrx
  • 19,980
  • 5
  • 34
  • 48
  • 1
    Do u have to add SND_FILENAME|SND_LOOP|SND_ASYNC in the import ? – Kevin.a Oct 24 '17 at 08:18
  • 2
    No, use commas to import them and the pipe `|` (bitwise or) to combine the flags as you you can see in the `play_sound` method. – skrx Oct 24 '17 at 08:20