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 mixer.music 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 mixer.music 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()

pygame.mixer.init()

screen = pygame.display.set_mode([64 0,48 0]) pygame.time.delay(1000)

pygame.mixer.music.load("bg music.mp3")

pygame.mixer.music.set volume(0.3)

pygame.mixer.music.play()

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

splat.set volume(0.5)

while 1:

for event in pygame.event.get():

if event.type == pygame.QUIT:

sys.exit()

Checks if the music is

if not pygame.mixer.music.get busy():

—--- done playing

splat.play()

pygame.time.delay(1000)

Waits a second for the

sys.exit()

"splat" sound to finish

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

0 0

Responses

  • 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
  • YORDA
    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
  • FATIMA
    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