0
# Audio and Sound
1
2
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.
3
4
## Capabilities
5
6
### Audio System Initialization
7
8
Initialize and configure the audio mixing system.
9
10
```python { .api }
11
def init(frequency: int = 22050, size: int = -16, channels: int = 2, buffer: int = 1024) -> None:
12
"""
13
Initialize the mixer module for audio playback.
14
15
Args:
16
frequency (int): Sample rate in Hz (22050 is common)
17
size (int): Sample size (-16 for 16-bit signed, 16 for unsigned)
18
channels (int): Number of channels (1=mono, 2=stereo)
19
buffer (int): Buffer size (smaller = less latency, more CPU)
20
"""
21
22
def pre_init(frequency: int = 22050, size: int = -16, channels: int = 2, buffer: int = 1024) -> None:
23
"""
24
Pre-initialize mixer settings before pygame.init().
25
26
Args: Same as init()
27
"""
28
29
def quit() -> None:
30
"""Uninitialize the mixer module."""
31
32
def get_init() -> tuple:
33
"""
34
Get current mixer initialization parameters.
35
36
Returns:
37
tuple: (frequency, format, channels) or None if not initialized
38
"""
39
```
40
41
### Sound Effects
42
43
Load and play sound effects with volume and channel control.
44
45
```python { .api }
46
class Sound:
47
def __init__(self, file_or_buffer):
48
"""
49
Load a sound from file or buffer.
50
51
Args:
52
file_or_buffer: File path, file object, or audio buffer
53
"""
54
55
def play(self, loops: int = 0, maxtime: int = 0, fade_ms: int = 0) -> pygame.mixer.Channel:
56
"""
57
Play the sound.
58
59
Args:
60
loops (int): Number of loops (-1 for infinite)
61
maxtime (int): Maximum play time in milliseconds (0 for no limit)
62
fade_ms (int): Fade in time in milliseconds
63
64
Returns:
65
pygame.mixer.Channel: Channel object playing the sound
66
"""
67
68
def stop(self) -> None:
69
"""Stop all instances of this sound."""
70
71
def fadeout(self, time: int) -> None:
72
"""
73
Fade out all instances of this sound.
74
75
Args:
76
time (int): Fade out time in milliseconds
77
"""
78
79
def set_volume(self, volume: float) -> None:
80
"""
81
Set volume for this sound.
82
83
Args:
84
volume (float): Volume level (0.0 to 1.0)
85
"""
86
87
def get_volume(self) -> float:
88
"""
89
Get volume of this sound.
90
91
Returns:
92
float: Current volume (0.0 to 1.0)
93
"""
94
95
def get_num_channels(self) -> int:
96
"""
97
Get number of channels this sound is playing on.
98
99
Returns:
100
int: Number of active channels
101
"""
102
103
def get_length(self) -> float:
104
"""
105
Get length of sound in seconds.
106
107
Returns:
108
float: Sound duration in seconds
109
"""
110
```
111
112
### Channel Management
113
114
Control individual audio mixing channels for advanced audio control.
115
116
```python { .api }
117
class Channel:
118
def __init__(self, id: int):
119
"""
120
Get a Channel object for controlling audio playback.
121
122
Args:
123
id (int): Channel number
124
"""
125
126
def play(self, sound: pygame.mixer.Sound, loops: int = 0, maxtime: int = 0, fade_ms: int = 0) -> None:
127
"""
128
Play a sound on this channel.
129
130
Args:
131
sound (pygame.mixer.Sound): Sound to play
132
loops (int): Number of loops
133
maxtime (int): Maximum play time in ms
134
fade_ms (int): Fade in time in ms
135
"""
136
137
def stop(self) -> None:
138
"""Stop playback on this channel."""
139
140
def pause(self) -> None:
141
"""Pause playback on this channel."""
142
143
def unpause(self) -> None:
144
"""Resume playback on this channel."""
145
146
def fadeout(self, time: int) -> None:
147
"""
148
Fade out sound on this channel.
149
150
Args:
151
time (int): Fade out time in milliseconds
152
"""
153
154
def set_volume(self, left: float, right: float = None) -> None:
155
"""
156
Set volume for this channel.
157
158
Args:
159
left (float): Left channel volume (0.0 to 1.0)
160
right (float, optional): Right channel volume (defaults to left)
161
"""
162
163
def get_volume(self) -> float:
164
"""
165
Get volume of this channel.
166
167
Returns:
168
float: Current volume (0.0 to 1.0)
169
"""
170
171
def get_busy(self) -> bool:
172
"""
173
Check if channel is currently playing.
174
175
Returns:
176
bool: True if channel is playing a sound
177
"""
178
179
def get_sound(self) -> pygame.mixer.Sound:
180
"""
181
Get sound currently playing on channel.
182
183
Returns:
184
pygame.mixer.Sound: Currently playing sound or None
185
"""
186
187
def queue(self, sound: pygame.mixer.Sound) -> None:
188
"""
189
Queue a sound to play after current sound finishes.
190
191
Args:
192
sound (pygame.mixer.Sound): Sound to queue
193
"""
194
195
def get_queue(self) -> pygame.mixer.Sound:
196
"""
197
Get queued sound.
198
199
Returns:
200
pygame.mixer.Sound: Queued sound or None
201
"""
202
```
203
204
### Global Mixer Control
205
206
Control overall audio system state and channel allocation.
207
208
```python { .api }
209
def stop() -> None:
210
"""Stop playback on all channels."""
211
212
def pause() -> None:
213
"""Pause playback on all channels."""
214
215
def unpause() -> None:
216
"""Resume playback on all channels."""
217
218
def fadeout(time: int) -> None:
219
"""
220
Fade out all sounds.
221
222
Args:
223
time (int): Fade out time in milliseconds
224
"""
225
226
def set_num_channels(count: int) -> None:
227
"""
228
Set number of mixing channels.
229
230
Args:
231
count (int): Number of channels (default 8)
232
"""
233
234
def get_num_channels() -> int:
235
"""
236
Get number of mixing channels.
237
238
Returns:
239
int: Current number of channels
240
"""
241
242
def set_reserved(count: int) -> None:
243
"""
244
Reserve channels for exclusive use.
245
246
Args:
247
count (int): Number of channels to reserve
248
"""
249
250
def find_channel(force: bool = False) -> pygame.mixer.Channel:
251
"""
252
Find an available channel.
253
254
Args:
255
force (bool): If True, stop longest running sound if no free channels
256
257
Returns:
258
pygame.mixer.Channel: Available channel or None
259
"""
260
261
def get_busy() -> bool:
262
"""
263
Check if any sounds are playing.
264
265
Returns:
266
bool: True if any sounds are currently playing
267
"""
268
```
269
270
### Music Streaming
271
272
High-quality music streaming for background music and large audio files.
273
274
```python { .api }
275
# pygame.mixer.music module functions
276
def load(file) -> None:
277
"""
278
Load a music file for streaming playback.
279
280
Args:
281
file: Music file path or file-like object
282
"""
283
284
def unload() -> None:
285
"""Unload current music and free resources."""
286
287
def play(loops: int = 0, start: float = 0.0, fade_ms: int = 0) -> None:
288
"""
289
Play loaded music.
290
291
Args:
292
loops (int): Number of loops (-1 for infinite)
293
start (float): Start position in seconds
294
fade_ms (int): Fade in time in milliseconds
295
"""
296
297
def rewind() -> None:
298
"""Restart music from beginning."""
299
300
def stop() -> None:
301
"""Stop music playback."""
302
303
def pause() -> None:
304
"""Pause music playback."""
305
306
def unpause() -> None:
307
"""Resume music playback."""
308
309
def fadeout(time: int) -> None:
310
"""
311
Fade out music.
312
313
Args:
314
time (int): Fade out time in milliseconds
315
"""
316
317
def set_volume(volume: float) -> None:
318
"""
319
Set music volume.
320
321
Args:
322
volume (float): Volume level (0.0 to 1.0)
323
"""
324
325
def get_volume() -> float:
326
"""
327
Get music volume.
328
329
Returns:
330
float: Current volume (0.0 to 1.0)
331
"""
332
333
def get_busy() -> bool:
334
"""
335
Check if music is playing.
336
337
Returns:
338
bool: True if music is currently playing
339
"""
340
341
def get_pos() -> int:
342
"""
343
Get playback position.
344
345
Returns:
346
int: Position in milliseconds (-1 if not supported)
347
"""
348
349
def queue(file) -> None:
350
"""
351
Queue music file to play after current music.
352
353
Args:
354
file: Music file to queue
355
"""
356
357
def set_endevent(type: int = 0) -> None:
358
"""
359
Set event to trigger when music ends.
360
361
Args:
362
type (int): Event type to post (0 to disable)
363
"""
364
365
def get_endevent() -> int:
366
"""
367
Get current music end event type.
368
369
Returns:
370
int: Event type or 0 if disabled
371
"""
372
```
373
374
## Supported Audio Formats
375
376
```python { .api }
377
# Sound formats (pygame.mixer.Sound)
378
# WAV, OGG (always supported)
379
# MP3, FLAC, MOD (if available)
380
381
# Music formats (pygame.mixer.music)
382
# OGG, MP3, MOD, XM, S3M, IT (format support varies by platform)
383
```
384
385
## Usage Examples
386
387
### Basic Sound Effects
388
389
```python
390
import pygame
391
392
pygame.mixer.init()
393
pygame.init()
394
395
# Load sound effects
396
try:
397
jump_sound = pygame.mixer.Sound("jump.wav")
398
explosion_sound = pygame.mixer.Sound("explosion.ogg")
399
except pygame.error as e:
400
print(f"Could not load sound: {e}")
401
402
screen = pygame.display.set_mode((800, 600))
403
clock = pygame.time.Clock()
404
405
running = True
406
while running:
407
for event in pygame.event.get():
408
if event.type == pygame.QUIT:
409
running = False
410
elif event.type == pygame.KEYDOWN:
411
if event.key == pygame.K_SPACE:
412
jump_sound.play()
413
elif event.key == pygame.K_x:
414
explosion_sound.play(loops=0, fade_ms=500)
415
416
clock.tick(60)
417
418
pygame.quit()
419
```
420
421
### Background Music
422
423
```python
424
import pygame
425
426
pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=1024)
427
pygame.init()
428
429
# Load and play background music
430
try:
431
pygame.mixer.music.load("background_music.ogg")
432
pygame.mixer.music.set_volume(0.7)
433
pygame.mixer.music.play(-1, fade_ms=3000) # Loop forever, fade in
434
except pygame.error as e:
435
print(f"Could not load music: {e}")
436
437
screen = pygame.display.set_mode((800, 600))
438
clock = pygame.time.Clock()
439
440
running = True
441
while running:
442
for event in pygame.event.get():
443
if event.type == pygame.QUIT:
444
running = False
445
elif event.type == pygame.KEYDOWN:
446
if event.key == pygame.K_m:
447
# Toggle music
448
if pygame.mixer.music.get_busy():
449
pygame.mixer.music.fadeout(1000)
450
else:
451
pygame.mixer.music.play(-1)
452
453
clock.tick(60)
454
455
pygame.quit()
456
```
457
458
### Advanced Channel Control
459
460
```python
461
import pygame
462
463
pygame.mixer.init()
464
pygame.init()
465
466
# Set up more channels for complex audio
467
pygame.mixer.set_num_channels(16)
468
469
# Reserve channels for important sounds
470
pygame.mixer.set_reserved(2) # Reserve first 2 channels
471
472
# Load sounds
473
laser_sound = pygame.mixer.Sound("laser.wav")
474
engine_sound = pygame.mixer.Sound("engine.wav")
475
476
# Get specific channels
477
engine_channel = pygame.mixer.Channel(0) # Reserved channel
478
effects_channel = pygame.mixer.Channel(2)
479
480
screen = pygame.display.set_mode((800, 600))
481
clock = pygame.time.Clock()
482
483
running = True
484
while running:
485
for event in pygame.event.get():
486
if event.type == pygame.QUIT:
487
running = False
488
elif event.type == pygame.KEYDOWN:
489
if event.key == pygame.K_e:
490
# Play engine sound on dedicated channel
491
if not engine_channel.get_busy():
492
engine_channel.play(engine_sound, loops=-1)
493
engine_channel.set_volume(0.5)
494
elif event.key == pygame.K_s:
495
# Stop engine
496
engine_channel.stop()
497
elif event.key == pygame.K_SPACE:
498
# Find any available channel for laser
499
channel = pygame.mixer.find_channel()
500
if channel:
501
channel.play(laser_sound)
502
503
clock.tick(60)
504
505
pygame.quit()
506
```
507
508
### Sound Volume and Fading
509
510
```python
511
import pygame
512
513
pygame.mixer.init()
514
pygame.init()
515
516
# Load sounds with different volume levels
517
quiet_sound = pygame.mixer.Sound("whisper.wav")
518
quiet_sound.set_volume(0.2)
519
520
loud_sound = pygame.mixer.Sound("explosion.wav")
521
loud_sound.set_volume(0.8)
522
523
ambient_sound = pygame.mixer.Sound("ambient.wav")
524
525
screen = pygame.display.set_mode((800, 600))
526
clock = pygame.time.Clock()
527
528
running = True
529
while running:
530
for event in pygame.event.get():
531
if event.type == pygame.QUIT:
532
running = False
533
elif event.type == pygame.KEYDOWN:
534
if event.key == pygame.K_1:
535
quiet_sound.play()
536
elif event.key == pygame.K_2:
537
loud_sound.play()
538
elif event.key == pygame.K_a:
539
# Play ambient sound with fade in
540
channel = ambient_sound.play(loops=-1, fade_ms=2000)
541
if channel:
542
# Set stereo panning (left=0.5, right=1.0)
543
channel.set_volume(0.5, 1.0)
544
elif event.key == pygame.K_f:
545
# Fade out all sounds
546
pygame.mixer.fadeout(1500)
547
548
clock.tick(60)
549
550
pygame.quit()
551
```
552
553
### Event-Driven Audio
554
555
```python
556
import pygame
557
558
pygame.mixer.init()
559
pygame.init()
560
561
# Create custom event for music end
562
MUSIC_END = pygame.event.custom_type()
563
pygame.mixer.music.set_endevent(MUSIC_END)
564
565
# Load playlist
566
playlist = ["song1.ogg", "song2.ogg", "song3.ogg"]
567
current_song = 0
568
569
# Start first song
570
pygame.mixer.music.load(playlist[current_song])
571
pygame.mixer.music.play()
572
573
screen = pygame.display.set_mode((800, 600))
574
clock = pygame.time.Clock()
575
576
running = True
577
while running:
578
for event in pygame.event.get():
579
if event.type == pygame.QUIT:
580
running = False
581
elif event.type == MUSIC_END:
582
# Load next song when current ends
583
current_song = (current_song + 1) % len(playlist)
584
pygame.mixer.music.load(playlist[current_song])
585
pygame.mixer.music.play()
586
print(f"Now playing: {playlist[current_song]}")
587
588
clock.tick(60)
589
590
pygame.quit()
591
```