Background Music
Part of the Sound and Game Feel section of Coddy's Pygame journey. Lesson 5 of 23.
Music is different from a sound effect. It is long, it loops, and only one track plays at a time. pygame has a separate player for it, pygame.mixer.music. It reads the file a bit at a time while it plays, instead of loading all of it like a Sound.
pygame.mixer.music.load("assets/music/level.ogg")
pygame.mixer.music.set_volume(0.6)
pygame.mixer.music.play(-1)load() picks the track. play() starts it; its number says how many more times to repeat it. play(-1) repeats it forever, which is what background music needs. play() or play(0) plays it once.
Start the music once, before the loop. Called in the loop, play() restarts the track from its beginning on every frame. The music has its own volume, set with pygame.mixer.music.set_volume(), from 0.0 to 1.0. Music that is a bit quieter than the effects lets the effects stand out.
Sound effects still play on top of the music: the coin sound and the track are heard together.
Challenge
EasyGive the coin game background music. Before the loop:
- Load
assets/music/level.oggwithpygame.mixer.music.load(). - Set the music volume to
0.6. - Start it with
play(-1)so it loops.
Try it yourself
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Coins")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)
coin_sound = pygame.mixer.Sound("assets/sounds/coin.ogg")
player = pygame.Rect(220, 160, 40, 40)
coin = pygame.Rect(100, 100, 16, 16)
score = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.x -= 5
if keys[pygame.K_RIGHT]:
player.x += 5
if keys[pygame.K_UP]:
player.y -= 5
if keys[pygame.K_DOWN]:
player.y += 5
player.clamp_ip(screen.get_rect())
if player.colliderect(coin):
score += 1
coin_sound.play()
coin.x = random.randint(20, 444)
coin.y = random.randint(50, 324)
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (255, 210, 60), coin)
pygame.draw.rect(screen, (90, 200, 120), player)
score_text = font.render(f"Coins: {score}", True, (240, 240, 240))
screen.blit(score_text, (10, 10))
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Sound and Game Feel
Practice on your own: Pygame playground