Playing background music

Background music is meant to play in the background while the game is being played. So once you start the background song, Pygame has to get ready to do other things, like moving sprites around or checking the mouse and keyboard for input. It doesn't wait for the song to finish.

But what if you want to know when the song ends? Maybe you want to start a different song or play another sound (like we want to do). How do you know when the music is done? Pygame has a way to tell you: you can ask the module if it's still busy playing a song. If it is, you know the song isn't done yet. If it is not busy, you know the song is done. Let's try that.

To find out if the music module is still busy playing a song, you use the module's get_busy() function. This will return the value True if it's still busy, and False if it isn't. This time, we'll make our program play the song, then play the sound effect, and then end the program automatically. Listing 19.4 shows you how.

Listing 19.4 Waiting for the end of the song import pygame, sys pygame.init()


screen = pygame.display.set_mode([64 0,48 0]) pygame.time.delay(1000)"bg music.mp3") volume(0.3)

splat = pygame.mixer.Sound("splat.wav")

splat.set volume(0.5)

while 1:

for event in pygame.event.get():

if event.type == pygame.QUIT:


Checks if the music is

if not busy():

—--- done playing


Waits a second for the


"splat" sound to finish

This code will play the song once, then play the sound effect, and then the program will end.

0 0


  • Kai
    How to play a backgroud music pygame?
    6 years ago
  • hanna petelius
    How to play music in python?
    6 years ago
  • henri
    How to make background music in pygame?
    6 years ago
    How to play sound in pygame?
    6 years ago
  • benjamin
    How to get background music in python?
    6 years ago
  • chelsea
    How to create background music pygame?
    6 years ago
    How to play background music on python tkinter?
    10 months ago
  • tesmi
    How do you let music play in the background of an naimation in python?
    7 months ago

Post a comment