Kivy切换按钮仅打开/关闭声音一次

2024-06-16 10:11:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图寻找答案,但运气不好

我试图在kivy中构建一个应用程序,当按钮被切换时,它会启动和停止声音。第一次切换按钮时,声音符合我的要求,但第二次按钮仅启动声音,但不停止声音

这是到目前为止我的代码

“代码”

class MainApp(App):

def build(self):
    layout = BoxLayout(padding=10)
    self.oceanButton = ToggleButton(text='Ocean',
    background_normal='C:/Users/micha/Desktop/Code/Soothing Sounds/picture/oceanpic.jpg')
    self.oceanButton.bind(on_press=self.on_press_button)
    layout.add_widget(self.oceanButton)

    return layout


def on_press_button(self, *args):
    waveSound = SoundLoader.load(
         'C:/Users/micha/Desktop/Code/Soothing Sounds/sounds/ocean.wav'
        )
    
    if self.oceanButton.state == 'down':
        waveSound.play()
        waveSound.loop = True
        print('On')
    else:
        waveSound.stop()
        print('Off')

Tags: 代码self声音ondefcode按钮users
1条回答
网友
1楼 · 发布于 2024-06-16 10:11:42

问题是on_press_button()方法总是创建Sound的新实例(使用SoundLoader)。因此,当ToggleButton状态不是down时,它在新实例上调用stop()方法,并且在上一次调用中创建的Sound继续播放

您可以通过保留对已创建的Sound实例的引用并使用该实例调用stop()来修复此问题:

def on_press_button(self, *args):
    if self.oceanButton.state == 'down':
        self.waveSound = SoundLoader.load(
             'C:/Users/micha/Desktop/Code/Soothing Sounds/sounds/ocean.wav'
            )
        self.waveSound.play()
        self.waveSound.loop = True
        print('On')
    else:
        self.waveSound.stop()
        print('Off')

相关问题 更多 >