使用 winsound 连续播放声音并单击按钮停止

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

我正尝试在 Python 3 中使用 winsound。 要启动声音,我是这样做的:

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

这只播放一次声音,但我想循环播放。是否有循环播放声音的内置功能?

下一步:在 tkinter 中我有一个带有命令的按钮:

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

给定的命令应该停止播放已经循环的声音。 这是函数:

def stopAlarm():
    #stop the alarm

简而言之,我想循环播放声音,并且能够停止播放声音,知道如何实现吗?

要使用 winsound 连续播放声音,您可以将 SND_FILENAME, SND_LOOP, SND_ASYNC 常量与按位或 | 组合:SND_FILENAME|SND_LOOP|SND_ASYNC.

要停止声音,您只需将 None 作为第一个参数传递给 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()