Chapter 14: The Audio System

The AudioPlayer struct forms the core of the audio system for this game. This system uses the sdl2::mixer module from the SDL2 library in Rust. It can load and play .mp3, .flac, .mod, and .ogg audio files. The AudioPlayer struct contains a single field - mixer_context.

An AudioPlayer is instantiated with a specific number of channels (numchans). The constructor function (new) initializes SDL2, opens an audio device with a specific frequency, chunk size, and number of channels.

It provides a method play that loads an audio file, plays it in a loop a given number of times and sets its volume. The play method returns a Channel that can be paused, resumed, or stopped using the respective methods in AudioPlayer.

When an AudioPlayer instance is dropped, it ends the currently playing music and prints a message to the console.

Last updated