切换音乐开/关Kivy

时间:2018-05-31 14:18:37

标签: python-3.x kivy togglebutton

这是我的.py文件的一部分。我希望on_state每次切换按钮时运行,但它不起作用。我将打印语句放入测试每个部分,它将打印" ONSTATE !!!"每次我切换按钮。但是这两个人都没有下来'或者'正常'各州印刷。

class MusicScreen(Screen):

enter = ObjectProperty(None)
text_input = ObjectProperty(None)
stop = ObjectProperty(None)
musicbutton = ToggleButton()

class MainApp(App):

def build(self):
    return presentation

def on_state(self, state, filename):
    print("ONSTATE!!!")
    sound = SoundLoader.load('/users/nolandonley/desktop/MP3/mus/' + filename + '.m4a')
    if state == "down":
        print("DOWN")
        sound.volume = .5
        sound.play()
    if state == "normal":
        print("normal")
        sound.stop()

以下是我项目的.kv文件。

<MusicScreen>:

text_input: text_input
id: "music"
name: "music"
BoxLayout:
    size: root.size
    pos: root.pos
    orientation: "vertical"
    FileChooserListView:
        id: filechooser
        rootpath: "/Users/nolandonley/desktop/MP3/mus"
        on_selection: text_input.text = self.selection and self.selection[0] or ''

    TextInput:
        id: text_input
        size_hint_y: None
        height: 50
        multiline: False
    ToggleButton:
        #pos: 44, 30
        size_hint: 1, .2
        text: "Play/Stop By File"
    ToggleButton:
        id: musicbutton
        #pos: 44, 30
        size_hint: 1, .2
        text: "Play/Stop By Title"
        on_state: app.on_state(self, text_input.text)

1 个答案:

答案 0 :(得分:2)

停止播放音乐

使用 ObjectProperty sound.unload()方法停止播放音乐。

main.py

class MainApp(App):
    sound = ObjectProperty(None, allownone=True)

    def build(self):
        return ScreenManagement()

    def on_state(self, state, filename):
        print("ONSTATE!!!")
        print("\tstate=", state)

        if self.sound is None:
            self.sound = SoundLoader.load(filename)

        # stop the sound if it's currently playing
        if self.sound.status != 'stop':
            self.sound.stop()

        if state == "down":
            self.sound.volume = .5
            self.sound.play()
        else:   # if state == "normal":
            if self.sound:
                self.sound.stop()
                self.sound.unload()
                self.sound = None

传递切换按钮的状态

它无法正常工作,因为您传递的是一个对象,即切换按钮的实例。

替换

on_state: app.on_state(self, text_input.text)

on_state: app.on_state(self.state, text_input.text)

注意

[Toggle Button][1]只有两种状态,即 正常 down 。因此,您不需要两个if语句。通过以下方式提高Kivy App的性能:

更换

if state == "down":
    print("DOWN")
    sound.volume = .5
    sound.play()
if state == "normal":
    print("normal")
    sound.stop()

使用:

print(state)
if state == "down":
    sound.volume = .5
    sound.play()
else:   # if state == "normal":
    sound.stop()