Python: How to Create a Music Player with Pygame

Have you ever considered using Python to design your own music player? You can simply include music playing capabilities in your Python applications using the Pygame module. You could load, play, and manipulate music files using the mixer module in Pygame, a well-known module for game creation and multimedia programming 😊

Before using Pygame, it must be installed on the computer. Open the terminal, type in the following command and press enter:

pip install pygame

Once Pygame is installed successfully, we could then write our music player:

import pygame

def play_music(file_path):
    """
    Play music from file_path until user enters 'q'
    """
    # initialize pygame mixer
    pygame.mixer.init()

    # load music file
    pygame.mixer.music.load(file_path)

    # play music file, -1 denotes indefinite repetition
    pygame.mixer.music.play(-1)

    # set volume
    pygame.mixer.music.set_volume(0.5)

    # wait for user input to stop music
    while True:
        response = input('Enter q to stop music:')
        if response.lower() == 'q':
            break

    # stop music
    pygame.mixer.music.stop()

    # uninitialize pygame mixer
    pygame.mixer.quit()

if __name__ == '__main__':
    # specify the path of the audio file
    file_path = 'audio.mp3'

    # play the music
    play_music(file_path)

I hope that’s been informative to you. If you wish to learn more about Python, please subscribe to our newsletter today and continue your Python learning journey with us!

Leave a Reply