Skip to content
Related Articles

Related Articles

Python – Add audio files in kivy

View Discussion
Improve Article
Save Article
  • Last Updated : 23 Jan, 2020

Kivy is a platform independent GUI tool in Python. Kivy is a tool used to build cross-platform applications in Python which can run on android, IOS, Linux, Windows.

Audio Widget:
This module is used to load audio files in kivy.

 from kivy.core.audio import SoundLoader 

Below is the code on how you can import an audio file in kivy.

NOTE:You can import audio files with only ‘.wav’ format.




from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.core.audio import SoundLoader
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
  
class Tester(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
  
    def play_sound(self):
        sound = SoundLoader.load('sampleaudio.wav')
        if sound:
            sound.play()
  
class SampleApp(App):
  
    def build(self):
        return Tester()
  
myApp = SampleApp()
myApp.run()

.kv file of the above code [Sample.kv]:




<Tester>:
    orientation: "vertical"
    spacing: 50
    space_x: self.size[0]/3
    canvas.before:
        Color:
            rgba: (0, 0, 0, 0)
        Rectangle:
            size: self.size
            pos: self.pos
  
    FloatLayout:
        orientation:'vertical'
        padding:100
        spacing:30
        Button:
            size_hint:0.6, 0.1
            pos_hint :{'center_x':0.5, 'center_y':0.3}
            text:'PLAY'
            bold:True
            background_color: (1, .36, .4, .55)
            on_release: root.play_sound()

Output:

The output of the following code will be as shown below which will play an audio file ‘sampleaudio.wav’ when we click the play button.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!