Playing Music in Pygame using Python
In this tutorial, we are going to see how to insert music or sound into our pygame file using Python. We can also play music in Python using Pygame. Before starting let us ensure where would this kind of concept is useful. when we create a game in Python using pygame that involves some characters where the character crashes or hit with bullets we would like to generate sound and to incorporate background music during the game this module is helpful.
Before we can start using our sound and music files we need to load them.
The syntax for loading music files and sound files is as follows.
The pygame can load WAV, MP3, OGG these are extensions of the sound file and take them as input to pygame.mixer.
Working with Sound and Music Files using pygame.mixer in Python
To incorporate sound files we use pygame.mixer.Sound(). This is assigned with an object as follows
soun_obj=pygame.mixer.Sound("bullet.wav") soun_obj.play() soun_obj.stop()
In the above example, we used bullet sound where
- soun_obj.play() is used to play the sound.
- soun_obj.stop() is used to stop the sound.
To incorporate music files we use pygame.mixer.music.load(). This can be used directly without creating an object.
pygame.mixer.music.load("helicopter.mp3") pygame.mixer.music.play() pygame.mixer.music.stop()
In the above example, we used helicopter sound as background music where
- pygame.mixer.music.play() is used to start the background music.
- pygame.mixer.music.stop() is used to stop the background music.
It will play music for 4 seconds only. Later, it will stop likewise you can specify how many numbers of seconds you want to play the music. By default, it is set to zero (0). we can play music as long as the pygame window is opened by using this statement
The following code will represent the working of sound and music files.
import pygame import sys pygame.init() display=pygame.display.set_mode((400,300)) pygame.display.set_caption("sound demo") pygame.mixer.music.load("ringtone.mp3") soun_obj=pygame.mixer.Sound("bullet.wav") pygame.mixer.music.play() soun_obj.play() while True: for eve in pygame.event.get(): if eve.type==pygame.QUIT: pygame.quit() sys.exit()
In the above code, we will get the blank screen with background music ringtone and bullet sound playing.we can stop the music by including stop() as mentioned above.
We can play more than one music each time by using a random module that helps us to play random music. The code is as follows
import random l=["helicopter.mp3","bird.mp3","ringtone.mp3"] pygame.mixer.music.load(random.choice(l))
It helps us to load different background music each time from the list we have created.
NOTE: The sound files and the Python file must be in the same folder
Music Files: (We can play both .wav and .mp3 file)