How to add Music Playlist in Pygame?


Pygame can handle audio, making it a great choice for creating and adding music playlists to our applications. Pygame is generally a Python library that is widely used for creating games and multimedia applications like a music player. In this article, we will be discussing steps to add a music playlist in Pygame, and create a simple program that will allow the user to play and change (previous or next songs) songs in the playlist.

Pygame relies on the SDL library (Simple DirectMedia Layer) for the audio processing. Therefore, to use pygame’s audio features, we must have SDL installed on our systems. We can download SDL library from the official website, or we can also download it through our system’s package manager.

How to add Music playlist in Pygame?

Below is the algorithm that we will follow to add music playlist in Pygame −

Algorithm

  • Step 1 − Import pygame and initialize it.

    The very initial step to add a music playlist in Pygame is to import the Pygame module and initialize it.

  • Step 2 − Load Music files

    After we have initialized the Pygame module, we can now load the music files that we want to play. Pygame supports a variety of audio formats that include WAV, MP3, and OGG. We will use the pygame.mixer.music.load(), to load music files.

  • Step 3 − Play music

    We will use the pygame.mixer.music.play() function to play the music file.

  • Step 4 − Create a music playlist

    We have seen how we can load and play music files, we can now create a music playlist by storing the filenames of the music files in the list.

Example

import pygame
# Initialize Pygame
pygame.init()
# Set up the screen (not needed for audio)
screen = pygame.display.set_mode((640, 480))
# Create a list of music files to play
music_files = ["song1.mp3", "song2.mp3", "song3.mp3"]

# Load the first song in the list
current_song_index = 0
pygame.mixer.music.load(music_files[current_song_index])

# Play the current song
pygame.mixer.music.play()

# Set up fonts for displaying song titles
font = pygame.font.SysFont("Arial", 24)

# Create buttons to skip to the next song and go back to the previous song
next_button_rect = pygame.Rect(500, 200, 100, 50)
next_button_text = font.render("Next", True, (255, 255, 255))
prev_button_rect = pygame.Rect(100, 200, 100, 50)
prev_button_text = font.render("Prev", True, (255, 255, 255))

# Start the game loop
while True:
   # Handle events (including button clicks)
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         # User clicked the "X" button, exit the game
         pygame.quit()
         quit()
      elif event.type == pygame.MOUSEBUTTONDOWN:
         # Check if the user clicked one of the buttons
         if next_button_rect.collidepoint(event.pos):
            # User clicked the "next" button, go to the next song in the list
            current_song_index += 1
            if current_song_index >= len(music_files):
               # If we've reached the end of the list, wrap around to the beginning
                  current_song_index = 0
                  pygame.mixer.music.load(music_files[current_song_index])
                  pygame.mixer.music.play()
            elif prev_button_rect.collidepoint(event.pos):
               # User clicked the "prev" button, go to the previous song in the list
               current_song_index -= 1
               if current_song_index < 0:
                  # If we've reached the beginning of the list, wrap around to the end
                  current_song_index = len(music_files) - 1
                  pygame.mixer.music.load(music_files[current_song_index])
                  pygame.mixer.music.play()

   # Draw the buttons and current song title on the screen
   screen.fill((0, 0, 0))
   pygame.draw.rect(screen, (255, 0, 0), next_button_rect)
   pygame.draw.rect(screen, (255, 0, 0), prev_button_rect)
   screen.blit(next_button_text, next_button_rect)
   screen.blit(prev_button_text, prev_button_rect)
   current_song_title = font.render(music_files[current_song_index], True, (255, 255, 255))

   screen.blit(current_song_title, (320 - current_song_title.get_width() // 2, 100 - current_song_title.get_height() // 2))

   # Update the screen
   pygame.display.update()

The above program creates a list of music files: song1.mp3, song2.mp3, song3.mp3 you will have to download mp3 files and replace them with song1, song2, and song 3. It also creates two buttons to skip to the next song or go back to the previous song. When the user clicks one of the buttons, the program maintains and updates the current song index and loads and plays the new song in the list for example if the person clicks on the next button then the program will update the list and the next song in the list will be played. The program will also display the current song that is playing on the screen.

Output

Open the command prompt and paste the below command −

python music.py

Music is the name of the file. Press enter after typing the above command.

The following screen will appear with 2 buttons on the screen and the name of the current song.

Conclusion

In conclusion, the Python library called Pygame provides a simple and easy-to-use interface for adding a music playlist to our applications. With the ability to load and play multiple audio files, we can easily create a music playlist and also we can add controls to change the songs. With a bit of creativity and knowledge of Pygame, we can even add some other features such as a shuffle button or a progress button. Overall, creating or adding a music playlist using Pygame can enhance the user experience in the game or other multimedia applications.

Updated on: 31-May-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements