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



我试着寻找这个问题的答案,但运气不佳。

我试图在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')

问题是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')

最新更新