How to Use Audio in Rust Game Development

Use the rodio crate to load audio files into a Source and play them through a Sink in Rust games.

Use the rodio crate to load and play audio files in Rust games. Add rodio to your Cargo.toml dependencies, then load an audio file into a Source and play it using a Sink.

use rodio::{Sink, Source};
use std::fs::File;
use std::io::BufReader;

fn main() {
    let (stream, device) = rodio::OutputStream::try_default().unwrap();
    let sink = Sink::try_new(&device).unwrap();

    let file = File::open("sound.mp3").unwrap();
    let source = rodio::source::Decoder::new(BufReader::new(file)).unwrap();

    sink.append(source);
    std::thread::sleep(std::time::Duration::from_secs(5));
}

Add this to Cargo.toml:

[dependencies]
rodio = "0.18"

This example assumes you have a file named sound.mp3 in your project directory.