Kivy Music Player with Python | Part -3

So this is Part 3 of the kivy music player series, in this part, we will see, how to make a progress bar and how we can update the current and total time for songs in our kivy music player.

So this is the last code that we write in part 2.

import os
import random
import kivy
kivy.require('2.0.0')
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivymd.uix.relativelayout import MDRelativeLayout
from kivymd.uix.button import MDIconButton
from kivymd.app import MDApp
from kivy.core.audio import SoundLoader
from kivy.clock import Clock
from kivy.core.window import Window
Window.size = (400,600)
class MyApp(MDApp):
    
    def build(self):
        layout = MDRelativeLayout(md_bg_color = [0,0.5,1,1])
        self.music_dir = 'F:/Project/Parts'
        music_files = os.listdir(self.music_dir)
        
        print(music_files)
        
        self.song_list = [x for x in music_files if x.endswith('mp3')]
        print(self.song_list)
        
        self.song_count = len(self.song_list)
        self.songlabel = Label(pos_hint={'center_x':0.5, 'center_y':.96},
                               size_hint=(1,1),
                               font_size=18)
        self.albumimage = Image(pos_hint={'center_x':0.5, 'center_y':0.55},
                               size_hint=(.8,.75))
        self.playbutton = MDIconButton(pos_hint={'center_x':0.4, 'center_y':0.05},
                                icon="play.png",
                                on_press = self.playaudio)
        
        self.stopbutton = MDIconButton(pos_hint={'center_x':0.55, 'center_y':0.05},
                                icon="stop.png",
                                on_press = self.stopaudio, disabled=True)
        layout.add_widget(self.songlabel)
        layout.add_widget(self.albumimage)
        layout.add_widget(self.playbutton)
        layout.add_widget(self.stopbutton)        
        Clock.schedule_once(self.playaudio)
        
        return layout
    def playaudio(self,obj):
        self.playbutton.disabled = True
        self.stopbutton.disabled = False
        self.song_title = self.song_list[random.randrange(0, self.song_count)]
        print(self.song_title)
        self.songlabel.text = "===== Playing ~ "+self.song_title[2:-4] +" ====="
        self.sound = SoundLoader.load('{}/{}'.format(self.music_dir, self.song_title))
        self.albumimage.source = self.song_title[0]+".jpg"
        self.sound.play()
    def stopaudio(self,obj):
        self.playbutton.disabled = False
        self.stopbutton.disabled = True
        self.sound.stop()
    
if __name__ == '__main__':
    MyApp().run()

Now import the kivy progress bar from the kivy UI library.

from kivy.uix.progressbar import ProgressBar

Now add the below code under the build function to set the current time label, total time label, and progress bar in our music player UI.

self.currenttime = Label(text = "00:00",
                                 pos_hint={'center_x':.16, 'center_y':.145},
                                 size_hint=(1,1),
                                 font_size=18)
self.totaltime = Label(text = "00:00",
                                 pos_hint={'center_x':0.84, 'center_y':.145},
                                 size_hint=(1,1),
                                 font_size=18)
    
self.progressbar = ProgressBar(max = 100,
                                 value = 0,
                                 pos_hint={'center_x':0.5, 'center_y':0.12},
                                 size_hint=(.8,.75))

Now add labels and a progress bar to the layout.

layout.add_widget(self.currenttime)
layout.add_widget(self.totaltime)
layout.add_widget(self.progressbar)

Now create two events to update the progress bar status and current time for the song.

self.progressbarEvent = Clock.schedule_interval(self.updateprogressbar,self.sound.length/60)
self.timeEvent = Clock.schedule_interval(self.settime,1)

The Above code will execute two function

  • updateprogressbar() – to update progress bar.
  • settime() – to update and set time.
def updateprogressbar(self,value):
    if self.progressbar.value < 100:
        self.progressbar.value +=1
def settime(self,t):
    current_time = time.strftime('%M:%S', time.gmtime(self.progressbar.value))
    total_time = time.strftime('%M:%S', time.gmtime(self.sound.length))
    self.currenttime.text = current_time
    self.totaltime.text = total_time

updateprogressbar() function will update the progress bar value by +1 at particular time interval.

settime() function will take the progress bar value and song length value to change it to the MM:SS format to show time for a progress bar.

Finally, update the stopaudio() function to set the progress bar value and timestamps to its original value or initial value.

def stopaudio(self,obj):
    self.playbutton.disabled = False
    self.stopbutton.disabled = True
    self.sound.stop()
    self.progressbarEvent.cancel()
    self.timeEvent.cancel()
    self.progressbar.value = 0
    self.currenttime.text = "00:00"
    self.totaltime.text = "00:00"

Final Code Upto this Point.

import os
import random
import time
import kivy
kivy.require('2.0.0')
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.progressbar import ProgressBar
from kivymd.uix.relativelayout import MDRelativeLayout
from kivymd.uix.button import MDIconButton
from kivymd.app import MDApp
from kivy.core.audio import SoundLoader
from kivy.clock import Clock
from kivy.core.window import Window
Window.size = (400,600)
class MyApp(MDApp):
    
    def build(self):
        layout = MDRelativeLayout(md_bg_color = [0,0.5,1,1])
        self.music_dir = 'F:/Project/Parts'
        music_files = os.listdir(self.music_dir)
        
        print(music_files)
        
        self.song_list = [x for x in music_files if x.endswith('mp3')]
        print(self.song_list)
        
        self.song_count = len(self.song_list)
        self.songlabel = Label(pos_hint={'center_x':0.5, 'center_y':.96},
                               size_hint=(1,1),
                               font_size=18)
        self.albumimage = Image(pos_hint={'center_x':0.5, 'center_y':0.55},
                               size_hint=(.8,.75))
        self.currenttime = Label(text = "00:00",
                               pos_hint={'center_x':.16, 'center_y':.145},
                               size_hint=(1,1),
                               font_size=18)
        self.totaltime = Label(text = "00:00",
                               pos_hint={'center_x':0.84, 'center_y':.145},
                               size_hint=(1,1),
                               font_size=18)
    
        self.progressbar = ProgressBar(max = 100,
                                       value = 0,
                                       pos_hint={'center_x':0.5, 'center_y':0.12},
                                       size_hint=(.8,.75))
        self.playbutton = MDIconButton(pos_hint={'center_x':0.4, 'center_y':0.05},
                                       icon="play.png",
                                       on_press = self.playaudio)
        
        self.stopbutton = MDIconButton(pos_hint={'center_x':0.55, 'center_y':0.05},
                                       icon="stop.png",
                                       on_press = self.stopaudio, disabled=True)
        layout.add_widget(self.songlabel)
        layout.add_widget(self.albumimage)
        layout.add_widget(self.currenttime)
        layout.add_widget(self.totaltime)
        layout.add_widget(self.progressbar)
        layout.add_widget(self.playbutton)
        layout.add_widget(self.stopbutton)        
        Clock.schedule_once(self.playaudio)
        
        return layout
    def playaudio(self,obj):
        self.playbutton.disabled = True
        self.stopbutton.disabled = False
        self.song_title = self.song_list[random.randrange(0, self.song_count)]
        print(self.song_title)
        self.songlabel.text = "===== Playing ~ "+self.song_title[2:-4] +" ====="
        self.sound = SoundLoader.load('{}/{}'.format(self.music_dir, self.song_title))
        self.albumimage.source = self.song_title[0]+".jpg"
        self.sound.play()
        self.progressbarEvent = Clock.schedule_interval(self.updateprogressbar,self.sound.length/60)
        self.timeEvent = Clock.schedule_interval(self.settime,1)
    def updateprogressbar(self,value):
        if self.progressbar.value < 100:
            self.progressbar.value +=1
    def settime(self,t):
        current_time = time.strftime('%M:%S', time.gmtime(self.progressbar.value))
        total_time = time.strftime('%M:%S', time.gmtime(self.sound.length))
        self.currenttime.text = current_time
        self.totaltime.text = total_time
            
    def stopaudio(self,obj):
        self.playbutton.disabled = False
        self.stopbutton.disabled = True
        self.sound.stop()
        self.progressbarEvent.cancel()
        self.timeEvent.cancel()
        self.progressbar.value = 0
        self.currenttime.text = "00:00"
        self.totaltime.text = "00:00"
    
if __name__ == '__main__':
    MyApp().run()
Shopping Cart