我试图寻找答案,但运气不好
我试图在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()
来修复此问题:相关问题 更多 >
编程相关推荐