Cross-platform library for developing multimedia applications and video games in Python built on top of SDL
Audio system including sound effects, music streaming, mixing channels, and volume control. Pygame's audio system supports multiple file formats and provides both simple sound playback and advanced mixing capabilities.
Initialize and configure the audio mixing system.
def init(frequency: int = 22050, size: int = -16, channels: int = 2, buffer: int = 1024) -> None:
"""
Initialize the mixer module for audio playback.
Args:
frequency (int): Sample rate in Hz (22050 is common)
size (int): Sample size (-16 for 16-bit signed, 16 for unsigned)
channels (int): Number of channels (1=mono, 2=stereo)
buffer (int): Buffer size (smaller = less latency, more CPU)
"""
def pre_init(frequency: int = 22050, size: int = -16, channels: int = 2, buffer: int = 1024) -> None:
"""
Pre-initialize mixer settings before pygame.init().
Args: Same as init()
"""
def quit() -> None:
"""Uninitialize the mixer module."""
def get_init() -> tuple:
"""
Get current mixer initialization parameters.
Returns:
tuple: (frequency, format, channels) or None if not initialized
"""Load and play sound effects with volume and channel control.
class Sound:
def __init__(self, file_or_buffer):
"""
Load a sound from file or buffer.
Args:
file_or_buffer: File path, file object, or audio buffer
"""
def play(self, loops: int = 0, maxtime: int = 0, fade_ms: int = 0) -> pygame.mixer.Channel:
"""
Play the sound.
Args:
loops (int): Number of loops (-1 for infinite)
maxtime (int): Maximum play time in milliseconds (0 for no limit)
fade_ms (int): Fade in time in milliseconds
Returns:
pygame.mixer.Channel: Channel object playing the sound
"""
def stop(self) -> None:
"""Stop all instances of this sound."""
def fadeout(self, time: int) -> None:
"""
Fade out all instances of this sound.
Args:
time (int): Fade out time in milliseconds
"""
def set_volume(self, volume: float) -> None:
"""
Set volume for this sound.
Args:
volume (float): Volume level (0.0 to 1.0)
"""
def get_volume(self) -> float:
"""
Get volume of this sound.
Returns:
float: Current volume (0.0 to 1.0)
"""
def get_num_channels(self) -> int:
"""
Get number of channels this sound is playing on.
Returns:
int: Number of active channels
"""
def get_length(self) -> float:
"""
Get length of sound in seconds.
Returns:
float: Sound duration in seconds
"""Control individual audio mixing channels for advanced audio control.
class Channel:
def __init__(self, id: int):
"""
Get a Channel object for controlling audio playback.
Args:
id (int): Channel number
"""
def play(self, sound: pygame.mixer.Sound, loops: int = 0, maxtime: int = 0, fade_ms: int = 0) -> None:
"""
Play a sound on this channel.
Args:
sound (pygame.mixer.Sound): Sound to play
loops (int): Number of loops
maxtime (int): Maximum play time in ms
fade_ms (int): Fade in time in ms
"""
def stop(self) -> None:
"""Stop playback on this channel."""
def pause(self) -> None:
"""Pause playback on this channel."""
def unpause(self) -> None:
"""Resume playback on this channel."""
def fadeout(self, time: int) -> None:
"""
Fade out sound on this channel.
Args:
time (int): Fade out time in milliseconds
"""
def set_volume(self, left: float, right: float = None) -> None:
"""
Set volume for this channel.
Args:
left (float): Left channel volume (0.0 to 1.0)
right (float, optional): Right channel volume (defaults to left)
"""
def get_volume(self) -> float:
"""
Get volume of this channel.
Returns:
float: Current volume (0.0 to 1.0)
"""
def get_busy(self) -> bool:
"""
Check if channel is currently playing.
Returns:
bool: True if channel is playing a sound
"""
def get_sound(self) -> pygame.mixer.Sound:
"""
Get sound currently playing on channel.
Returns:
pygame.mixer.Sound: Currently playing sound or None
"""
def queue(self, sound: pygame.mixer.Sound) -> None:
"""
Queue a sound to play after current sound finishes.
Args:
sound (pygame.mixer.Sound): Sound to queue
"""
def get_queue(self) -> pygame.mixer.Sound:
"""
Get queued sound.
Returns:
pygame.mixer.Sound: Queued sound or None
"""Control overall audio system state and channel allocation.
def stop() -> None:
"""Stop playback on all channels."""
def pause() -> None:
"""Pause playback on all channels."""
def unpause() -> None:
"""Resume playback on all channels."""
def fadeout(time: int) -> None:
"""
Fade out all sounds.
Args:
time (int): Fade out time in milliseconds
"""
def set_num_channels(count: int) -> None:
"""
Set number of mixing channels.
Args:
count (int): Number of channels (default 8)
"""
def get_num_channels() -> int:
"""
Get number of mixing channels.
Returns:
int: Current number of channels
"""
def set_reserved(count: int) -> None:
"""
Reserve channels for exclusive use.
Args:
count (int): Number of channels to reserve
"""
def find_channel(force: bool = False) -> pygame.mixer.Channel:
"""
Find an available channel.
Args:
force (bool): If True, stop longest running sound if no free channels
Returns:
pygame.mixer.Channel: Available channel or None
"""
def get_busy() -> bool:
"""
Check if any sounds are playing.
Returns:
bool: True if any sounds are currently playing
"""High-quality music streaming for background music and large audio files.
# pygame.mixer.music module functions
def load(file) -> None:
"""
Load a music file for streaming playback.
Args:
file: Music file path or file-like object
"""
def unload() -> None:
"""Unload current music and free resources."""
def play(loops: int = 0, start: float = 0.0, fade_ms: int = 0) -> None:
"""
Play loaded music.
Args:
loops (int): Number of loops (-1 for infinite)
start (float): Start position in seconds
fade_ms (int): Fade in time in milliseconds
"""
def rewind() -> None:
"""Restart music from beginning."""
def stop() -> None:
"""Stop music playback."""
def pause() -> None:
"""Pause music playback."""
def unpause() -> None:
"""Resume music playback."""
def fadeout(time: int) -> None:
"""
Fade out music.
Args:
time (int): Fade out time in milliseconds
"""
def set_volume(volume: float) -> None:
"""
Set music volume.
Args:
volume (float): Volume level (0.0 to 1.0)
"""
def get_volume() -> float:
"""
Get music volume.
Returns:
float: Current volume (0.0 to 1.0)
"""
def get_busy() -> bool:
"""
Check if music is playing.
Returns:
bool: True if music is currently playing
"""
def get_pos() -> int:
"""
Get playback position.
Returns:
int: Position in milliseconds (-1 if not supported)
"""
def queue(file) -> None:
"""
Queue music file to play after current music.
Args:
file: Music file to queue
"""
def set_endevent(type: int = 0) -> None:
"""
Set event to trigger when music ends.
Args:
type (int): Event type to post (0 to disable)
"""
def get_endevent() -> int:
"""
Get current music end event type.
Returns:
int: Event type or 0 if disabled
"""# Sound formats (pygame.mixer.Sound)
# WAV, OGG (always supported)
# MP3, FLAC, MOD (if available)
# Music formats (pygame.mixer.music)
# OGG, MP3, MOD, XM, S3M, IT (format support varies by platform)import pygame
pygame.mixer.init()
pygame.init()
# Load sound effects
try:
jump_sound = pygame.mixer.Sound("jump.wav")
explosion_sound = pygame.mixer.Sound("explosion.ogg")
except pygame.error as e:
print(f"Could not load sound: {e}")
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
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:
jump_sound.play()
elif event.key == pygame.K_x:
explosion_sound.play(loops=0, fade_ms=500)
clock.tick(60)
pygame.quit()import pygame
pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=1024)
pygame.init()
# Load and play background music
try:
pygame.mixer.music.load("background_music.ogg")
pygame.mixer.music.set_volume(0.7)
pygame.mixer.music.play(-1, fade_ms=3000) # Loop forever, fade in
except pygame.error as e:
print(f"Could not load music: {e}")
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
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_m:
# Toggle music
if pygame.mixer.music.get_busy():
pygame.mixer.music.fadeout(1000)
else:
pygame.mixer.music.play(-1)
clock.tick(60)
pygame.quit()import pygame
pygame.mixer.init()
pygame.init()
# Set up more channels for complex audio
pygame.mixer.set_num_channels(16)
# Reserve channels for important sounds
pygame.mixer.set_reserved(2) # Reserve first 2 channels
# Load sounds
laser_sound = pygame.mixer.Sound("laser.wav")
engine_sound = pygame.mixer.Sound("engine.wav")
# Get specific channels
engine_channel = pygame.mixer.Channel(0) # Reserved channel
effects_channel = pygame.mixer.Channel(2)
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
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_e:
# Play engine sound on dedicated channel
if not engine_channel.get_busy():
engine_channel.play(engine_sound, loops=-1)
engine_channel.set_volume(0.5)
elif event.key == pygame.K_s:
# Stop engine
engine_channel.stop()
elif event.key == pygame.K_SPACE:
# Find any available channel for laser
channel = pygame.mixer.find_channel()
if channel:
channel.play(laser_sound)
clock.tick(60)
pygame.quit()import pygame
pygame.mixer.init()
pygame.init()
# Load sounds with different volume levels
quiet_sound = pygame.mixer.Sound("whisper.wav")
quiet_sound.set_volume(0.2)
loud_sound = pygame.mixer.Sound("explosion.wav")
loud_sound.set_volume(0.8)
ambient_sound = pygame.mixer.Sound("ambient.wav")
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
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_1:
quiet_sound.play()
elif event.key == pygame.K_2:
loud_sound.play()
elif event.key == pygame.K_a:
# Play ambient sound with fade in
channel = ambient_sound.play(loops=-1, fade_ms=2000)
if channel:
# Set stereo panning (left=0.5, right=1.0)
channel.set_volume(0.5, 1.0)
elif event.key == pygame.K_f:
# Fade out all sounds
pygame.mixer.fadeout(1500)
clock.tick(60)
pygame.quit()import pygame
pygame.mixer.init()
pygame.init()
# Create custom event for music end
MUSIC_END = pygame.event.custom_type()
pygame.mixer.music.set_endevent(MUSIC_END)
# Load playlist
playlist = ["song1.ogg", "song2.ogg", "song3.ogg"]
current_song = 0
# Start first song
pygame.mixer.music.load(playlist[current_song])
pygame.mixer.music.play()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == MUSIC_END:
# Load next song when current ends
current_song = (current_song + 1) % len(playlist)
pygame.mixer.music.load(playlist[current_song])
pygame.mixer.music.play()
print(f"Now playing: {playlist[current_song]}")
clock.tick(60)
pygame.quit()