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.
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.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
Loading the song.
Setting the volume.
you can set volume between 0 to 1, 1 is maximum.
Start playing the song.
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
To resume the song
To set the volume (again use while playing)
v is a variable, it store the value of the user input while music is playing.
To stop the song
# 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
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,