Need help - bevy 0.16.1 with random select of file not work - what did I wrong?

⚓ Rust    📅 2025-06-27    👤 surdeus    👁️ 8      

surdeus

Warning

This post was published 43 days ago. The information described in this article may have changed.

Hi,

my target is: select random a mp3 file in directory: assets/sounds
and start playing this....
if hardcode one file name the sound is played
but wanna have a random select file

the source code


use std::{fs, process::exit};
use rand::prelude::IndexedRandom;

use bevy::prelude::*;

fn main() {

    getsoundfile();

    App::new()
        .add_plugins(DefaultPlugins)
        .add_systems(Startup, playsound)
        .run();

}


fn getsoundfile() {
    let mp3_files: Vec<_> = fs::read_dir("assets/sounds")
        .unwrap()
        .filter_map(|entry| entry.ok())
        .collect();
    
    let mut rng = rand::rng();


    if let Some(random_file) = mp3_files.choose(&mut rng) {

        println!("Zufällig ausgewählte MP3-Datei: {}", random_file.path().display());
    } else {
        println!("Keine MP3-Dateien gefunden!");
        exit(99);
    }

}


fn playsound(mut commands: Commands, asset_server: Res<AssetServer>) {
    // MP3-Datei laden (im Ordner "assets/sounds/")
    let randsoundfile: &str = getsoundfile();
    let audio_handle = asset_server.load(randsoundfile.as_str());
//    let audio_handle = asset_server.load(&randsoundfile);
    commands.spawn(AudioPlayer::new(audio_handle));
}

Error:

error[E0308]: mismatched types
  --> src/main.rs:40:31
   |
40 |     let randsoundfile: &str = getsoundfile();
   |                        ----   ^^^^^^^^^^^^^^ expected `&str`, found `()`
   |                        |
   |                        expected due to this

error[E0658]: use of unstable library feature `str_as_str`
  --> src/main.rs:41:56
   |
41 |     let audio_handle = asset_server.load(randsoundfile.as_str());
   |                                                        ^^^^^^
   |
   = note: see issue #130366 <https://github.com/rust-lang/rust/issues/130366> for more information

Some errors have detailed explanations: E0308, E0658.
For more information about an error, try `rustc --explain E0308`.
error: could not compile `rand_select` (bin "rand_select") due to 2 previous errors

10 posts - 4 participants

Read full topic

🏷️ rust_feed