Pygame is a set of Python modules designed to create games and multimedia programs.
In this shot, we will go through how to play an audio file in Pygame.
Pygame comes with a module called mixer
, with which we will play an audio file.
Pygame
module with pip
.pip install pygame
.mp3
extension.mixer
module from the pygame
module.mixer
.The above steps are enough to play the audio, but we can pause
, resume
, and stop
the music playback.
The following code snippet will play the audio using mixer
in Pygame.
mixer
from pygame
.mixer
with mixer.init()
.True
to run the loop infinitely. We will stop this loop when the user stops the music.
pause
, resume
, and stop
the music.from pygame import mixer#Instantiate mixermixer.init()#Load audio filemixer.music.load('song.mp3')print("music started playing....")#Set preferred volumemixer.music.set_volume(0.2)#Play the musicmixer.music.play()#Infinite loopwhile True:print("------------------------------------------------------------------------------------")print("Press 'p' to pause the music")print("Press 'r' to resume the music")print("Press 'e' to exit the program")#take user inputuserInput = input(" ")if userInput == 'p':# Pause the musicmixer.music.pause()print("music is paused....")elif userInput == 'r':# Resume the musicmixer.music.unpause()print("music is resumed....")elif userInput == 'e':# Stop the music playbackmixer.music.stop()print("music is stopped....")break