Open In App
Related Articles

Python – Add audio files in kivy

Improve Article
Improve
Save Article
Save
Like Article
Like

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.


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 23 Jan, 2020
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials