Pygame includes a dedicated module, pygame.mixer.music, for managing background music playback within your games.
The set_volume() Function: Your Primary Volume Control
The pygame.mixer.music.set_volume() function serves as the central method for adjusting music volume. It accepts a floating-point value between 0.0 (representing silence) and 1.0 (representing maximum volume) to provide fine-grained control.
We can set the volume in pygame by pygame.mixer.music.set_volume(set_volume)
volume can be 0 to 1 and in between. like 0.5 or 0.7
This is the example code. Customize by changing the set_volume variable! Remember, your ‘sound.mp3’ file needs to be in the same folder as your code, or you can change the filename in the code.
import pygame
import os
pygame.init()
screen = pygame.display.set_mode((400, 400))
# Load your background music (make sure 'sound.mp3' is in the right place)
pygame.mixer.music.load('sound.mp3')
# Start playing your music
pygame.mixer.music.play()
# Set starting volume (0.0 is silent, 1.0 is full volume)
set_volume = 0.8
pygame.mixer.music.set_volume(set_volume)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
# End Pygame
pygame.quit()
If you are interested in more control and feature in pygame music, you can also read this article
https://medium.com/@01one/create-your-own-music-player-in-pygame-7d8d81d8580c