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:

  • Enqueue an MP3 to the playlist,
  • Remove an MP3 from the playlist,
  • Load a playlist from a text file,
  • Save a playlist on a text file,
  • Shuffle all the songs in the playlist,
  • Display all the tracks from 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:

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

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

You can test this code as follows:

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

You can test this code as follows:

This method will return the length of the tracks list.

To test this method:

To calculate the total duration of a playlist we need to add the duration of each of its tracks.

To test this method:

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:

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

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

To reset a playlist we just need to reset its tracks list to an empty list.

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

To check is a playlist is empty we can check if the length of its tracks list is equal to 0.

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

Did you like this challenge?

Click on a star to rate it!

Average rating 4.3 / 5. Vote count: 6

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

As you found this challenge interesting...

Follow us on social media!

Tagged with: