Audio
Audio in raylib-rs sits behind a separate device token:
RaylibAudio.
Call RaylibAudio::init_audio_device() to open the audio device and get the token.
Every audio resource — Wave, Sound, Music, AudioStream — is created through
methods on RaylibAudio and carries a lifetime tied to the RaylibAudio token.
The borrow checker enforces that no audio resource outlives the device, so teardown
order is correct by construction.
Note on the plan’s wording. The plan refers to “AudioHandle” — the real type name in the codebase is
RaylibAudio(raylib::core::audio::RaylibAudio).
API surface
RaylibAudio::init_audio_device— open the audio device; returnsResult<RaylibAudio, …>. Panics if called twice.Wave— loaded wave data (raw PCM). Create viaRaylibAudio::new_wave.Sound— short audio clip ready for playback. Create viaRaylibAudio::new_sound.Music— audio stream for longer tracks. Create viaRaylibAudio::new_music.AudioStream— raw PCM stream for custom audio generation. Create viaRaylibAudio::new_audio_stream.Sound::play— play aSoundto completion (fire and forget).Music::play_stream— begin streaming aMusictrack; callupdate_music_streameach frame.AudioStream::is_processed— check whether the stream buffer needs refilling.
Example
extern crate raylib;
use raylib::prelude::*;
use raylib::core::audio::RaylibAudio;
fn main() {
let (mut rl, thread) = raylib::init()
.size(640, 480)
.title("Audio demo")
.build();
// Open the audio device.
let audio = RaylibAudio::init_audio_device()
.expect("failed to init audio device");
// Load a short sound effect; Sound is lifetime-bound to `audio`.
let sound = audio.new_sound("assets/coin.wav")
.expect("failed to load sound");
while !rl.window_should_close() {
if rl.is_key_pressed(KeyboardKey::KEY_SPACE) {
sound.play();
}
let mut d = rl.begin_drawing(&thread);
d.clear_background(Color::RAYWHITE);
d.draw_text("Press SPACE to play a sound", 10, 10, 20, Color::DARKGRAY);
}
// `sound` is dropped before `audio` — the compiler enforces this via lifetime.
// `audio` drop calls CloseAudioDevice.
}
Gotchas
RaylibAudiomust outlive every audio resource. The lifetime parameters onWave,Sound,Music, andAudioStreamare not just documentation — the compiler will reject code that dropsRaylibAudiowhile any resource is still live.- The audio callback was removed in 6.0. The old per-sample callback API is gone.
Use
AudioStreamwithis_processed/update_audio_streamfor custom PCM generation. - WS6-prep soundness fix. The unsound default
Soundimpl (backlog #277) was removed.Soundno longer implementsDefault.
See also
- RAII and resources — how lifetime-bound resources fit the broader RAII model.
RaylibAudiodocs.rs /Sounddocs.rs
Showcase examples
Showcase examples that exercise this module: