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.

Was this article helpful?

0 0
100 Bowling Tips

100 Bowling Tips

Playing bowling with your friends can help you decide if it is indeed the hobby that you want to invest your time on today. Aside from that, it can help you get a better feel of the sport. More importantly, when you play with your friends, it would become a more fun activity, which you can look forward to each week.

Get My Free Ebook


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

Post a comment