Python – Add audio files in kivy

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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()

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

<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()

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.