Python Game Development library providing comprehensive multimedia functionality for creating games and interactive applications.
—
Complete audio subsystem supporting sound effects, music playback, and multi-channel mixing. Handles various audio formats with volume control and channel management.
Core functions for initializing and configuring the audio system.
def init(frequency: int = 22050, size: int = -16, channels: int = 2, buffer: int = 512) -> None:
"""
Initialize the mixer module.
Parameters:
frequency: Sample rate in Hz (22050, 44100, etc.)
size: Bit depth (-16 for 16-bit signed, 16 for unsigned, -8/8 for 8-bit)
channels: Number of audio channels (1=mono, 2=stereo)
buffer: Buffer size in samples (smaller = lower latency, higher CPU)
"""
def pre_init(frequency: int = 22050, size: int = -16, channels: int = 2, buffersize: int = 4096) -> None:
"""
Pre-initialize mixer settings before pygame.init().
Parameters:
frequency: Sample rate in Hz
size: Bit depth
channels: Number of audio channels
buffersize: Buffer size in bytes
"""
def quit() -> None:
"""Uninitialize the mixer module."""
def get_init() -> tuple[int, int, int] | None:
"""
Get mixer initialization settings.
Returns:
tuple[int, int, int] | None: (frequency, format, channels) or None if not initialized
"""The Sound class represents individual sound effects and audio clips.
class Sound:
def __init__(self, file: str | bytes):
"""
Load sound from file or buffer.
Parameters:
file: Filename or bytes buffer containing audio data
"""
def play(self, loops: int = 0, maxtime: int = 0, fade_ms: int = 0) -> Channel:
"""
Play sound on available channel.
Parameters:
loops: Number of additional times to play (-1 for infinite)
maxtime: Maximum play time in milliseconds (0 for no limit)
fade_ms: Fade in time in milliseconds
Returns:
Channel: Channel object sound is playing on
"""
def stop(self) -> None:
"""Stop all instances of this sound."""
def fadeout(self, time: int) -> None:
"""
Fade out sound over time.
Parameters:
time: Fade time in milliseconds
"""
def set_volume(self, value: float) -> None:
"""
Set sound volume.
Parameters:
value: Volume from 0.0 to 1.0
"""
def get_volume(self) -> float:
"""
Get sound volume.
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 sound length in seconds.
Returns:
float: Sound duration in seconds
"""
def get_raw(self) -> bytes:
"""
Get raw audio data.
Returns:
bytes: Raw audio sample data
"""Channel objects control individual audio streams for mixing multiple sounds.
class Channel:
def __init__(self, id: int):
"""
Channel object for audio mixing.
Parameters:
id: Channel ID number
"""
def play(self, Sound: Sound, loops: int = 0, maxtime: int = 0, fade_ms: int = 0) -> None:
"""
Play sound on this channel.
Parameters:
Sound: Sound object to play
loops: Number of additional loops (-1 for infinite)
maxtime: Maximum play time in milliseconds
fade_ms: Fade in time in milliseconds
"""
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 channel over time.
Parameters:
time: Fade time in milliseconds
"""
def set_volume(self, volume: float) -> None:
"""
Set channel volume.
Parameters:
volume: Volume from 0.0 to 1.0
"""
def get_volume(self) -> float:
"""
Get channel volume.
Returns:
float: Current volume (0.0 to 1.0)
"""
def get_busy(self) -> bool:
"""
Check if channel is playing.
Returns:
bool: True if channel is actively playing
"""
def get_sound(self) -> Sound | None:
"""
Get sound playing on channel.
Returns:
Sound | None: Currently playing sound or None
"""
def queue(self, Sound: Sound) -> None:
"""
Queue sound to play after current sound finishes.
Parameters:
Sound: Sound to queue
"""
def get_queue(self) -> Sound | None:
"""
Get queued sound.
Returns:
Sound | None: Queued sound or None
"""
def set_endevent(self, type: int | None = None) -> None:
"""
Set event to post when playback ends.
Parameters:
type: Event type to post, or None to disable
"""
def get_endevent(self) -> int:
"""
Get end event type.
Returns:
int: Event type posted when playback ends
"""Functions for controlling the overall mixer state and channel management.
def stop() -> None:
"""Stop playback on all channels."""
def pause() -> None:
"""Pause playback on all channels."""
def unpause() -> None:
"""Resume playback on all paused channels."""
def fadeout(time: int) -> None:
"""
Fade out all channels over time.
Parameters:
time: Fade time in milliseconds
"""
def set_num_channels(count: int) -> None:
"""
Set number of mixing channels.
Parameters:
count: Number of channels (default is 8)
"""
def get_num_channels() -> int:
"""
Get number of mixing channels.
Returns:
int: Current number of channels
"""
def set_reserved(count: int) -> int:
"""
Reserve channels for specific use.
Parameters:
count: Number of channels to reserve
Returns:
int: Number of channels successfully reserved
"""
def find_channel(force: bool = False) -> Channel | None:
"""
Find available channel for playback.
Parameters:
force: If True, stop oldest sound to free channel
Returns:
Channel | None: Available channel or None if all busy
"""
def get_busy() -> bool:
"""
Check if any channels are playing.
Returns:
bool: True if any channel is actively playing
"""Functions for playing longer audio files as background music (separate from sound effects).
def load(filename: str) -> None:
"""
Load music file for playback.
Parameters:
filename: Music file path
"""
def unload() -> None:
"""Unload currently loaded music."""
def play(loops: int = 0, start: float = 0.0, fade_ms: int = 0) -> None:
"""
Play loaded music.
Parameters:
loops: Number of additional loops (-1 for infinite)
start: Starting position in seconds
fade_ms: 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 paused music."""
def fadeout(time: int) -> None:
"""
Fade out music over time.
Parameters:
time: Fade time in milliseconds
"""
def set_volume(volume: float) -> None:
"""
Set music volume.
Parameters:
volume: Volume from 0.0 to 1.0
"""
def get_volume() -> float:
"""
Get music volume.
Returns:
float: Current music volume (0.0 to 1.0)
"""
def get_busy() -> bool:
"""
Check if music is playing.
Returns:
bool: True if music is actively playing
"""
def set_pos(pos: float) -> None:
"""
Set music playback position.
Parameters:
pos: Position in seconds
"""
def get_pos() -> int:
"""
Get music playback position.
Returns:
int: Position in milliseconds (-1 if not playing)
"""
def queue(filename: str) -> None:
"""
Queue music file to play after current music.
Parameters:
filename: Music file to queue
"""import pygame
pygame.mixer.init()
# Load sound effects
jump_sound = pygame.mixer.Sound("jump.wav")
coin_sound = pygame.mixer.Sound("coin.wav")
explosion_sound = pygame.mixer.Sound("explosion.wav")
# Play sounds
jump_sound.play()
# Play with parameters
coin_sound.play(loops=2) # Play 3 times total
explosion_sound.play(fade_ms=500) # Fade in over 500ms
# Control volume
jump_sound.set_volume(0.7) # 70% volume
# Get sound information
print(f"Jump sound length: {jump_sound.get_length():.2f} seconds")
print(f"Coin sound volume: {coin_sound.get_volume()}")
pygame.mixer.quit()import pygame
pygame.mixer.init()
# Load and play background music
pygame.mixer.music.load("background.ogg")
pygame.mixer.music.play(-1) # Loop infinitely
# Control music
pygame.mixer.music.set_volume(0.5) # 50% volume
# Check if music is playing
if pygame.mixer.music.get_busy():
print("Music is playing")
# Fade out music over 3 seconds
pygame.mixer.music.fadeout(3000)
pygame.mixer.quit()import pygame
pygame.mixer.init()
# Set number of mixing channels
pygame.mixer.set_num_channels(16)
# Reserve first 4 channels for important sounds
pygame.mixer.set_reserved(4)
# Load sounds
laser_sound = pygame.mixer.Sound("laser.wav")
engine_sound = pygame.mixer.Sound("engine.wav")
# Play on specific channel
channel = pygame.mixer.Channel(0)
channel.play(engine_sound, loops=-1) # Loop engine sound
# Find available channel
free_channel = pygame.mixer.find_channel()
if free_channel:
free_channel.play(laser_sound)
# Control channel
channel.set_volume(0.3)
if channel.get_busy():
print("Channel 0 is playing")
# Queue sound to play after current
channel.queue(laser_sound)
pygame.mixer.quit()import pygame
pygame.mixer.pre_init(frequency=44100, size=-16, channels=2, buffersize=1024)
pygame.mixer.init()
# Load sound with volume control
sound = pygame.mixer.Sound("sound.wav")
sound.set_volume(0.8)
# Play with end event notification
SOUND_END = pygame.event.custom_type()
channel = sound.play()
channel.set_endevent(SOUND_END)
# Event loop to handle sound completion
running = True
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == SOUND_END:
print("Sound finished playing")
clock.tick(60)
pygame.mixer.quit()import pygame
pygame.mixer.init()
# Supported formats vary by platform, commonly supported:
# - WAV (uncompressed)
# - OGG Vorbis (compressed, recommended)
# - MP3 (may require additional libraries)
try:
# Try loading different formats
wav_sound = pygame.mixer.Sound("sound.wav")
print("WAV loaded successfully")
except pygame.error as e:
print(f"Failed to load WAV: {e}")
try:
ogg_sound = pygame.mixer.Sound("sound.ogg")
print("OGG loaded successfully")
except pygame.error as e:
print(f"Failed to load OGG: {e}")
# Music supports more formats than Sound
try:
pygame.mixer.music.load("music.mp3")
print("MP3 music loaded successfully")
except pygame.error as e:
print(f"Failed to load MP3: {e}")
pygame.mixer.quit()Audio format and configuration constants:
# Sample rates (Hz)
FREQUENCY_11025: int = 11025
FREQUENCY_22050: int = 22050
FREQUENCY_44100: int = 44100
# Bit depths
FORMAT_U8: int = 8 # 8-bit unsigned
FORMAT_S8: int = -8 # 8-bit signed
FORMAT_U16: int = 16 # 16-bit unsigned
FORMAT_S16: int = -16 # 16-bit signed (recommended)
# Channel counts
CHANNELS_MONO: int = 1 # Mono
CHANNELS_STEREO: int = 2 # StereoInstall with Tessl CLI
npx tessl i tessl/pypi-pygame-ce