How to play an audio file in Pygame
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.
Pre-requisites
- Download and install the latest Python version.
- Install the
Pygamemodule withpip.
pip install pygame
- Download any audio file ending with the
.mp3extension.
Implementation
Steps
- Import the
mixermodule from thepygamemodule. - Instantiate
mixer. - Load the audio file.
- Set desired volume.
- Play the music.
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.
- Line 1: Import
mixerfrompygame. - Line 4: Instantiate
mixerwithmixer.init(). - Line 7: Load the audio file by providing the path.
- Line 12: Set your desired volume.
- Line 15: Play the music.
- Line 18: Use while
Trueto run the loop infinitely. We will stop this loop when the user stops the music.- Line 20 to 22: Instructions to be displayed while audio is playing, so that user can
pause,resume, andstopthe music. - Line 25: Take user input
- Line 27 to 42: Use if-else condition to check user-entered input.
- Line 20 to 22: Instructions to be displayed while audio is playing, so that user can
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