Menu
CoddyTech

Sound Volume

Part of the Sound and Game Feel section of Coddy's Pygame journey. Lesson 3 of 23.

Every Sound has its own volume, from 0.0 (silent) to 1.0 (as loud as the file). A new Sound starts at 1.0. Change it with set_volume():

step_sound.set_volume(0.3)

Use it to balance a game. A footstep that plays all the time should be quiet; a rare explosion can be loud. A value above 1.0 counts as 1.0, so set_volume(5) plays at full volume, not five times louder.

A settings screen often counts the volume from 0 to 10, which reads better on the screen. Divide by 10 to get the Sound's value:

volume = 5
click_sound.set_volume(volume / 10)

The Sound keeps its volume until you set it again. When the player changes volume, call set_volume() again, or the Sound plays at the old level. get_volume() tells you the level a Sound has now.

challenge icon

Challenge

Easy

Up and Down change volume from 0 to 10, and Space plays the click so you can hear it. Make the click follow the setting:

  1. After volume = 5, call click_sound.set_volume(volume / 10).
  2. Call it again each time Up or Down changes volume.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Volume")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)

click_sound = pygame.mixer.Sound("assets/sounds/click.ogg")
volume = 5

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_UP and volume < 10:
                volume += 1
            elif event.key == pygame.K_DOWN and volume > 0:
                volume -= 1
            elif event.key == pygame.K_SPACE:
                click_sound.play()

    screen.fill((30, 30, 46))
    label = font.render(f"Volume: {volume}", True, (240, 240, 240))
    screen.blit(label, (40, 120))
    for i in range(10):
        color = (90, 200, 120) if i < volume else (60, 60, 80)
        pygame.draw.rect(screen, color, (40 + i * 40, 170, 32, 40))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

All lessons in Sound and Game Feel

Practice on your own: Pygame playground