Load a Sound
Part of the Sound and Game Feel section of Coddy's Pygame journey. Lesson 1 of 23.
pygame plays short sounds through pygame.mixer.Sound. Give it the path of a sound file and you get a Sound object:
jump_sound = pygame.mixer.Sound("assets/sounds/jump.ogg")pygame.init() starts the mixer, so make your Sounds after it. Make each Sound once, before the loop. Loading reads the file from disk; inside the loop it would read it 60 times a second.
When the moment comes, call play():
jump_sound.play()play() starts the sound and returns at once. The game keeps running while you hear it, and the same Sound can play again before it ends.
The assets/sounds/ folder holds the sounds you can use: jump, coin, powerup, laser, explosion, hit and more, all .ogg files. Open the Assets tab beside the game to hear them.
Challenge
EasyThe green square jumps when you press Space. Make it play a sound:
- Before the loop, load
assets/sounds/jump.oggintojump_sound. - Call
jump_sound.play()where the jump starts, next tospeed_y = -14.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Jump")
clock = pygame.time.Clock()
player = pygame.Rect(220, 280, 40, 40)
speed_y = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and player.bottom == 320:
speed_y = -14
speed_y += 1
player.y += speed_y
if player.bottom > 320:
player.bottom = 320
speed_y = 0
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (80, 80, 100), (0, 320, 480, 40))
pygame.draw.rect(screen, (90, 200, 120), player)
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Sound and Game Feel
Practice on your own: Pygame playground