How to control music volume in pygame

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

Related Posts

Send Desktop notification from pygame
April 29, 2024

For notification handling we will use plyer library We will add this functionality in our pygame code The complete code import pygame import sys from pygame.locals import * from plyer import notification pygame.init() clock = pygame.time.Clock() user_display = pygame.display.Info() width, height = 800, 600 screen = pygame.display.set_mode((width, height)) background = (255, 255, 255) red = […]

Pygame Project: Create the simplest digital clock
April 28, 2024

We will use python datetime module for our clock; We get the current time and separate the time into hour minutes and second. First get the current time Get the time in hour, minute and second Now got our clock time components. It will be like this import datetime current_time = datetime.datetime.now() hour = current_time.hour […]

Simulate Bird Flocking Behavior with pygame: Algorithm and Code Explained
March 23, 2024

Bird flocking is a wonderful example of how simple behaviors can lead to complex, beautiful patterns in nature. We’ll learn the key principles behind this flocking behavior and write a python program to simulate this wonderful phenomenon. The principles Bird Flocking Simulation Algorithm Setting Up the Simulation Each Frame of the Simulation The pygame example […]