I have a folder with a lot of MP3 files and I would like to create a Rust program that plays the files in a random order. (Note: I have two levels of folders.)
I want my program to be cross-platform (it must work on Windows and Linux) and portable (it must not depend on an installed program like VLC, Windows Media Player, ...).
I have written this program with the rodio
library:
use std::io::Cursor;
use rodio::{Decoder, OutputStream, source::Source};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let (_stream, stream_handle) = OutputStream::try_default().unwrap();
let sound_data = include_bytes!("song.mp3");
let source = Decoder::new_mp3(Cursor::new(&sound_data[..])).unwrap();
stream_handle.play_raw(source.convert_samples())?;
std::thread::sleep(std::time::Duration::from_secs(240));
Ok(())
}
but the program can only play one file.
I would need a HashMap
with the key being the file name and the value being a slice representing the file content.
You can use the include-dir crate. It is somewhat similar to include_bytes
but works on directories:
use include_dir::{include_dir, Dir};
static SONGS: Dir = include_dir!("../songs");
// get a file
let sound_data = SONGS.get_file("song.mp3").unwrap().contents();