user286508
user286508

Reputation: 29

Kivy Buttons- Play sound on click

I have looked at a few answers but I can't really make heads or tails of them. When any of the buttons are pressed I want it to play "beep.wav". Another problem I have is with the "return layout", where exactly should I be putting that in terms of indentation. Many thanks, Michael.

import kivy
import random
from kivy.core.audio import SoundLoader
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout


def callback(instance):
        print('The button <%s> is being pressed' % instance.text)

red = [1,0,0,1]
green = [0,1,0,1]
blue =  [0,0,1,1]
purple = [1,0,1,1]

class Buttons(App):
    def Orientation(self, orient):
        self.orient = orient

    def build(self):
        layout = BoxLayout(padding=0, orientation=self.orient)
        colors = [red, green, blue, purple]

        for i in range(4):
            btn = Button(text="Test Button %s" % (i+1), background_color=random.choice(colors))
            layout.add_widget(btn)
            btn.bind(on_press=btn_pressed) 
        return layout

    def btn_pressed():
        sound = SoundLoader.load('beep.wav')
        sound.play()

if __name__ == "__main__":
    app = Buttons()
    app.Orientation(orient="vertical")
    app.run()

Upvotes: 1

Views: 4056

Answers (2)

Mike Rehner
Mike Rehner

Reputation: 1

I would create a .kv file

<Buttons>:
   Button1:
       background_color: 1,0,0,1
       text: "Play Sound"
       on_press: root.btn_pressed()
Button2: etc

That might isolate the problem. Then remove the return

if_name__ == 'main':
    Button().run()

Upvotes: 0

inclement
inclement

Reputation: 29460

btn.bind(on_press=btn_pressed)

Make this btn.bind(on_press=self.btn_pressed), it is not a local variable but can be accessed this way as a class method.

Another problem I have is with the "return layout", where exactly should I be putting that in terms of indentation.

The real question is where in the program logic should it be returned? The answer is that the method should always return it because you always want it to be the root widget, so your current position (the final line of the method, which is always called) is fine.

Upvotes: 2

Related Questions