How to Make Music Player in Python [Step by Step]

Hello Internet People, today we gonna see how to make Music Player in Python. This music player plays your song and you can pause, resume, set volume while playing songs and then you can stop the music.

Installation

pip install pygame

In python, game programming is done in pygame and it is one of the best modules for doing so.

In order to play music/audio files in pygame, pygame.mixer is used (pygame module for loading and playing sounds).

What we gonna do (Logic)

This module contains classes for loading Sound objects and controlling playback. There are basically four steps in order to do so:

Starting the mixer

mixer.init()

Loading the song.

mixer.music.load("your-song.mp3")

Setting the volume.

mixer.music.set_volume(0.6)

you can set volume between 0 to 1, 1 is maximum.

Start playing the song.

mixer.music.play()

We use while loop in order to ask the user to Pause, Resume, Set volume, and Stop the music while music is playing. For that following methods are useful.

To pause the song

mixer.music.pause()

To resume the song

mixer.music.unpause()

To set the volume (again use while playing)

mixer.music.set_volume(v)

v is a variable, it store the value of the user input while music is playing.

To stop the song

mixer.music.stop()

Code

# Music player in python

from pygame import mixer

mixer.init()
# --------------------------Path of your music
mixer.music.load("PYAR-HUA-IKRAAR-HUA.mp3")
mixer.music.set_volume(0.5)
mixer.music.play()

while True:
    print("Press 'p' to pause")
    print("Press 'r' to resume")
    print("Press 'v' set volume")
    print("Press 'e' to exit")

    ch = input("['p','r','v','e']>>>")

    if ch == "p":
        mixer.music.pause()
    elif ch == "r":
        mixer.music.unpause()
    elif ch == "v":
        v = float(input("Enter volume(0 to 1): "))
        mixer.music.set_volume(v)
    elif ch == "e":
        mixer.music.stop()
        break

# Follow @code_snail

Output

how to make music player in python output

Hope you like this simple music player in python. Try your self and play the song. You can tag me (@code_snail) also on your Instagram story. Share with your friends :)

Other pythonic stuff,