or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdaudio-system.mdcore-system.mdcursor-management.mddisplay-graphics.mdevent-handling.mdindex.mdinput-systems.mdmath-operations.mdmidi-support.mdsprites-game-objects.mdtyping-support.md

audio-system.mddocs/

0

# Audio System

1

2

Complete audio subsystem supporting sound effects, music playback, and multi-channel mixing. Handles various audio formats with volume control and channel management.

3

4

## Capabilities

5

6

### Audio System Initialization

7

8

Core functions for initializing and configuring the audio system.

9

10

```python { .api }

11

def init(frequency: int = 22050, size: int = -16, channels: int = 2, buffer: int = 512) -> None:

12

"""

13

Initialize the mixer module.

14

15

Parameters:

16

frequency: Sample rate in Hz (22050, 44100, etc.)

17

size: Bit depth (-16 for 16-bit signed, 16 for unsigned, -8/8 for 8-bit)

18

channels: Number of audio channels (1=mono, 2=stereo)

19

buffer: Buffer size in samples (smaller = lower latency, higher CPU)

20

"""

21

22

def pre_init(frequency: int = 22050, size: int = -16, channels: int = 2, buffersize: int = 4096) -> None:

23

"""

24

Pre-initialize mixer settings before pygame.init().

25

26

Parameters:

27

frequency: Sample rate in Hz

28

size: Bit depth

29

channels: Number of audio channels

30

buffersize: Buffer size in bytes

31

"""

32

33

def quit() -> None:

34

"""Uninitialize the mixer module."""

35

36

def get_init() -> tuple[int, int, int] | None:

37

"""

38

Get mixer initialization settings.

39

40

Returns:

41

tuple[int, int, int] | None: (frequency, format, channels) or None if not initialized

42

"""

43

```

44

45

### Sound Object

46

47

The Sound class represents individual sound effects and audio clips.

48

49

```python { .api }

50

class Sound:

51

def __init__(self, file: str | bytes):

52

"""

53

Load sound from file or buffer.

54

55

Parameters:

56

file: Filename or bytes buffer containing audio data

57

"""

58

59

def play(self, loops: int = 0, maxtime: int = 0, fade_ms: int = 0) -> Channel:

60

"""

61

Play sound on available channel.

62

63

Parameters:

64

loops: Number of additional times to play (-1 for infinite)

65

maxtime: Maximum play time in milliseconds (0 for no limit)

66

fade_ms: Fade in time in milliseconds

67

68

Returns:

69

Channel: Channel object sound is playing on

70

"""

71

72

def stop(self) -> None:

73

"""Stop all instances of this sound."""

74

75

def fadeout(self, time: int) -> None:

76

"""

77

Fade out sound over time.

78

79

Parameters:

80

time: Fade time in milliseconds

81

"""

82

83

def set_volume(self, value: float) -> None:

84

"""

85

Set sound volume.

86

87

Parameters:

88

value: Volume from 0.0 to 1.0

89

"""

90

91

def get_volume(self) -> float:

92

"""

93

Get sound volume.

94

95

Returns:

96

float: Current volume (0.0 to 1.0)

97

"""

98

99

def get_num_channels(self) -> int:

100

"""

101

Get number of channels this sound is playing on.

102

103

Returns:

104

int: Number of active channels

105

"""

106

107

def get_length(self) -> float:

108

"""

109

Get sound length in seconds.

110

111

Returns:

112

float: Sound duration in seconds

113

"""

114

115

def get_raw(self) -> bytes:

116

"""

117

Get raw audio data.

118

119

Returns:

120

bytes: Raw audio sample data

121

"""

122

```

123

124

### Channel Management

125

126

Channel objects control individual audio streams for mixing multiple sounds.

127

128

```python { .api }

129

class Channel:

130

def __init__(self, id: int):

131

"""

132

Channel object for audio mixing.

133

134

Parameters:

135

id: Channel ID number

136

"""

137

138

def play(self, Sound: Sound, loops: int = 0, maxtime: int = 0, fade_ms: int = 0) -> None:

139

"""

140

Play sound on this channel.

141

142

Parameters:

143

Sound: Sound object to play

144

loops: Number of additional loops (-1 for infinite)

145

maxtime: Maximum play time in milliseconds

146

fade_ms: Fade in time in milliseconds

147

"""

148

149

def stop(self) -> None:

150

"""Stop playback on this channel."""

151

152

def pause(self) -> None:

153

"""Pause playback on this channel."""

154

155

def unpause(self) -> None:

156

"""Resume playback on this channel."""

157

158

def fadeout(self, time: int) -> None:

159

"""

160

Fade out channel over time.

161

162

Parameters:

163

time: Fade time in milliseconds

164

"""

165

166

def set_volume(self, volume: float) -> None:

167

"""

168

Set channel volume.

169

170

Parameters:

171

volume: Volume from 0.0 to 1.0

172

"""

173

174

def get_volume(self) -> float:

175

"""

176

Get channel volume.

177

178

Returns:

179

float: Current volume (0.0 to 1.0)

180

"""

181

182

def get_busy(self) -> bool:

183

"""

184

Check if channel is playing.

185

186

Returns:

187

bool: True if channel is actively playing

188

"""

189

190

def get_sound(self) -> Sound | None:

191

"""

192

Get sound playing on channel.

193

194

Returns:

195

Sound | None: Currently playing sound or None

196

"""

197

198

def queue(self, Sound: Sound) -> None:

199

"""

200

Queue sound to play after current sound finishes.

201

202

Parameters:

203

Sound: Sound to queue

204

"""

205

206

def get_queue(self) -> Sound | None:

207

"""

208

Get queued sound.

209

210

Returns:

211

Sound | None: Queued sound or None

212

"""

213

214

def set_endevent(self, type: int | None = None) -> None:

215

"""

216

Set event to post when playback ends.

217

218

Parameters:

219

type: Event type to post, or None to disable

220

"""

221

222

def get_endevent(self) -> int:

223

"""

224

Get end event type.

225

226

Returns:

227

int: Event type posted when playback ends

228

"""

229

```

230

231

### Global Mixer Control

232

233

Functions for controlling the overall mixer state and channel management.

234

235

```python { .api }

236

def stop() -> None:

237

"""Stop playback on all channels."""

238

239

def pause() -> None:

240

"""Pause playback on all channels."""

241

242

def unpause() -> None:

243

"""Resume playback on all paused channels."""

244

245

def fadeout(time: int) -> None:

246

"""

247

Fade out all channels over time.

248

249

Parameters:

250

time: Fade time in milliseconds

251

"""

252

253

def set_num_channels(count: int) -> None:

254

"""

255

Set number of mixing channels.

256

257

Parameters:

258

count: Number of channels (default is 8)

259

"""

260

261

def get_num_channels() -> int:

262

"""

263

Get number of mixing channels.

264

265

Returns:

266

int: Current number of channels

267

"""

268

269

def set_reserved(count: int) -> int:

270

"""

271

Reserve channels for specific use.

272

273

Parameters:

274

count: Number of channels to reserve

275

276

Returns:

277

int: Number of channels successfully reserved

278

"""

279

280

def find_channel(force: bool = False) -> Channel | None:

281

"""

282

Find available channel for playback.

283

284

Parameters:

285

force: If True, stop oldest sound to free channel

286

287

Returns:

288

Channel | None: Available channel or None if all busy

289

"""

290

291

def get_busy() -> bool:

292

"""

293

Check if any channels are playing.

294

295

Returns:

296

bool: True if any channel is actively playing

297

"""

298

```

299

300

### Music Playback

301

302

Functions for playing longer audio files as background music (separate from sound effects).

303

304

```python { .api }

305

def load(filename: str) -> None:

306

"""

307

Load music file for playback.

308

309

Parameters:

310

filename: Music file path

311

"""

312

313

def unload() -> None:

314

"""Unload currently loaded music."""

315

316

def play(loops: int = 0, start: float = 0.0, fade_ms: int = 0) -> None:

317

"""

318

Play loaded music.

319

320

Parameters:

321

loops: Number of additional loops (-1 for infinite)

322

start: Starting position in seconds

323

fade_ms: Fade in time in milliseconds

324

"""

325

326

def rewind() -> None:

327

"""Restart music from beginning."""

328

329

def stop() -> None:

330

"""Stop music playback."""

331

332

def pause() -> None:

333

"""Pause music playback."""

334

335

def unpause() -> None:

336

"""Resume paused music."""

337

338

def fadeout(time: int) -> None:

339

"""

340

Fade out music over time.

341

342

Parameters:

343

time: Fade time in milliseconds

344

"""

345

346

def set_volume(volume: float) -> None:

347

"""

348

Set music volume.

349

350

Parameters:

351

volume: Volume from 0.0 to 1.0

352

"""

353

354

def get_volume() -> float:

355

"""

356

Get music volume.

357

358

Returns:

359

float: Current music volume (0.0 to 1.0)

360

"""

361

362

def get_busy() -> bool:

363

"""

364

Check if music is playing.

365

366

Returns:

367

bool: True if music is actively playing

368

"""

369

370

def set_pos(pos: float) -> None:

371

"""

372

Set music playback position.

373

374

Parameters:

375

pos: Position in seconds

376

"""

377

378

def get_pos() -> int:

379

"""

380

Get music playback position.

381

382

Returns:

383

int: Position in milliseconds (-1 if not playing)

384

"""

385

386

def queue(filename: str) -> None:

387

"""

388

Queue music file to play after current music.

389

390

Parameters:

391

filename: Music file to queue

392

"""

393

```

394

395

## Usage Examples

396

397

### Basic Sound Effects

398

399

```python

400

import pygame

401

402

pygame.mixer.init()

403

404

# Load sound effects

405

jump_sound = pygame.mixer.Sound("jump.wav")

406

coin_sound = pygame.mixer.Sound("coin.wav")

407

explosion_sound = pygame.mixer.Sound("explosion.wav")

408

409

# Play sounds

410

jump_sound.play()

411

412

# Play with parameters

413

coin_sound.play(loops=2) # Play 3 times total

414

explosion_sound.play(fade_ms=500) # Fade in over 500ms

415

416

# Control volume

417

jump_sound.set_volume(0.7) # 70% volume

418

419

# Get sound information

420

print(f"Jump sound length: {jump_sound.get_length():.2f} seconds")

421

print(f"Coin sound volume: {coin_sound.get_volume()}")

422

423

pygame.mixer.quit()

424

```

425

426

### Background Music

427

428

```python

429

import pygame

430

431

pygame.mixer.init()

432

433

# Load and play background music

434

pygame.mixer.music.load("background.ogg")

435

pygame.mixer.music.play(-1) # Loop infinitely

436

437

# Control music

438

pygame.mixer.music.set_volume(0.5) # 50% volume

439

440

# Check if music is playing

441

if pygame.mixer.music.get_busy():

442

print("Music is playing")

443

444

# Fade out music over 3 seconds

445

pygame.mixer.music.fadeout(3000)

446

447

pygame.mixer.quit()

448

```

449

450

### Channel Management

451

452

```python

453

import pygame

454

455

pygame.mixer.init()

456

457

# Set number of mixing channels

458

pygame.mixer.set_num_channels(16)

459

460

# Reserve first 4 channels for important sounds

461

pygame.mixer.set_reserved(4)

462

463

# Load sounds

464

laser_sound = pygame.mixer.Sound("laser.wav")

465

engine_sound = pygame.mixer.Sound("engine.wav")

466

467

# Play on specific channel

468

channel = pygame.mixer.Channel(0)

469

channel.play(engine_sound, loops=-1) # Loop engine sound

470

471

# Find available channel

472

free_channel = pygame.mixer.find_channel()

473

if free_channel:

474

free_channel.play(laser_sound)

475

476

# Control channel

477

channel.set_volume(0.3)

478

if channel.get_busy():

479

print("Channel 0 is playing")

480

481

# Queue sound to play after current

482

channel.queue(laser_sound)

483

484

pygame.mixer.quit()

485

```

486

487

### Advanced Audio Control

488

489

```python

490

import pygame

491

492

pygame.mixer.pre_init(frequency=44100, size=-16, channels=2, buffersize=1024)

493

pygame.mixer.init()

494

495

# Load sound with volume control

496

sound = pygame.mixer.Sound("sound.wav")

497

sound.set_volume(0.8)

498

499

# Play with end event notification

500

SOUND_END = pygame.event.custom_type()

501

channel = sound.play()

502

channel.set_endevent(SOUND_END)

503

504

# Event loop to handle sound completion

505

running = True

506

clock = pygame.time.Clock()

507

508

while running:

509

for event in pygame.event.get():

510

if event.type == pygame.QUIT:

511

running = False

512

elif event.type == SOUND_END:

513

print("Sound finished playing")

514

515

clock.tick(60)

516

517

pygame.mixer.quit()

518

```

519

520

### Audio Format Support

521

522

```python

523

import pygame

524

525

pygame.mixer.init()

526

527

# Supported formats vary by platform, commonly supported:

528

# - WAV (uncompressed)

529

# - OGG Vorbis (compressed, recommended)

530

# - MP3 (may require additional libraries)

531

532

try:

533

# Try loading different formats

534

wav_sound = pygame.mixer.Sound("sound.wav")

535

print("WAV loaded successfully")

536

except pygame.error as e:

537

print(f"Failed to load WAV: {e}")

538

539

try:

540

ogg_sound = pygame.mixer.Sound("sound.ogg")

541

print("OGG loaded successfully")

542

except pygame.error as e:

543

print(f"Failed to load OGG: {e}")

544

545

# Music supports more formats than Sound

546

try:

547

pygame.mixer.music.load("music.mp3")

548

print("MP3 music loaded successfully")

549

except pygame.error as e:

550

print(f"Failed to load MP3: {e}")

551

552

pygame.mixer.quit()

553

```

554

555

## Constants

556

557

Audio format and configuration constants:

558

559

```python { .api }

560

# Sample rates (Hz)

561

FREQUENCY_11025: int = 11025

562

FREQUENCY_22050: int = 22050

563

FREQUENCY_44100: int = 44100

564

565

# Bit depths

566

FORMAT_U8: int = 8 # 8-bit unsigned

567

FORMAT_S8: int = -8 # 8-bit signed

568

FORMAT_U16: int = 16 # 16-bit unsigned

569

FORMAT_S16: int = -16 # 16-bit signed (recommended)

570

571

# Channel counts

572

CHANNELS_MONO: int = 1 # Mono

573

CHANNELS_STEREO: int = 2 # Stereo

574

```