MP3 Playlist Class

iPodThe aim of this challenge is to implement a Class in Python to maintain an MP3 Playlist. This class could be used when developing the software for a music App on a smartphone or an mp3 player.

This MP3 playlist will be stored as a queue of MP3 tracks. When new tracks are being added to the playlist, they are enqueued at the end of the playlist. The key features that we will implement within this class are the ability to:

    Load a playlist from a text file,
    Display all the tracks from the playlist,
    Enqueue an MP3 to the playlist,
    Remove an MP3 from the playlist,
    Save a playlist on a text file,
    Shuffle all the songs in the playlist,
    Count the number of tracks in the playlist,
    Calculate the total duration of the playlist,
    Empty/Reset the playlist,
    Check if the playlist is empty.

Here is the class diagram for this project:
mp3-playlist-class

Python Code

We have started the code used to load a mp3 playlist from a text file.
Your task is to complete this code to implement all the methods mentioned above.

Solution (Step by step)

load() & save()enqueue()remove()getNumberOfTracks()getTotalDuration()shuffle()reset()isEmpty()
The load() and save() methods are used to load a playlist from a CSV file and save it on the CSV file. The save method() will overwrite the playlist if it already exists or create a new file if the file does not exists.

Here is the code to add to the Playlist class:

def load(self):
    self.tracks = []
    print("Loading tracks from CSV file.")
    file = open(self.filename,"r")
    for line in file:
      fields = line.split(";")
      track = Track(fields[0],fields[1],int(fields[2]))
      self.tracks.append(track)    
    file.close()
    
def save(self):
    print("Saving your playlist...")
    file = open(self.filename,"w")
    for track in self.tracks:
      file.write(track.title + ";" + track.artist + ";" + str(track.duration)+ ";")
    file.close()
    print("Playlist saved!")

In the main program we can test our load() and save() methods using the following code:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()
myPlaylist.view()

#Add or remove tracks or shuffle the playlist... using the enqueue(), remove() and shuffle() methods.

myPlaylist.save()
The enqueue() method from the Playlist class is used to append a track at the end of the tracks list:

def enqueue(self, track):
    self.tracks.append(track)

You can test this code as follows:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()

newTrack = Track("Wonderwall","Oasis",245)
myPlaylist.enqueue(newTrack)
myPlaylist.view()

myPlaylist.save()
The remove() method from the Playlist class is used to remove a track from the track list:

def removeTrack(self, track):
    self.tracks.remove(track)

You can test this code as follows:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()

myPlaylist.view()
myPlaylist.removeTrack(myPlaylist.tracks[2]) #This will remove the third track from the playlist!
myPlaylist.view()
This method will return the length of the tracks list.

def getNumberOfTracks(self):
    return len(self.tracks)

To test this method:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()

numberOfTracks = myPlaylist.getNumberOfTracks()
print("This playlist has " + str(numberOfTracks) + " tracks!")
To calculate the total duration of a playlist we need to add the duration of each of its tracks.

def getTotalDuration(self):
    duration = 0
    for track in self.tracks:
      duration += track.duration
    return duration

To test this method:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()

duration = myPlaylist.getTotalDuration()
print("This playlist lasts " + str(duration) + " seconds!")
The shuffle method just needs to shuffle the list of tracks using the shuffle() function from the random library.
We will hence need to import the random library by adding the following line at the top of the playlist.py file:

import random

Then we will add the following method to the Playlist class:

def shuffle(self):
  random.shuffle(self.tracks)

In the main program we can test our shuffle method using the following code:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()

myPlaylist.shuffle()
myPlaylist.view()
To reset a playlist we just need to reset its tracks list to an empty list.

def reset(self):
  self.tracks = []

In the main program we can test our reset method using the following code:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()

myPlaylist.reset()
myPlaylist.view()
To check is a playlist is empty we can check if the length of its tracks list is equal to 0.

def isEmpty(self):
  return len(self.tracks)==0

In the main program we can test our reset method using the following code:

from playlist import Track, Playlist

myPlaylist = Playlist("Pop Music","pop_music.csv")
myPlaylist.load()

if myPlaylist.isEmpty():
   print("Your playlist is empty.")

myPlaylist.reset()

if myPlaylist.isEmpty():
   print("Your playlist is empty.")

myPlaylist.view()

Did you like this challenge?

Click on a star to rate it!

Average rating 4.1 / 5. Vote count: 55

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: