How can I load all the audio files inside a folder using Bevy?

918 views Asked by At

I'm trying to make a music player where the user can play any audio file inside a folder. To do this, I'm trying to spawn entities containing a Music component and an Sound(Handle<AudioSource>) component. In the Bevy examples, I saw this line of code that seemed to be what I wanted:

// You can load all assets in a folder like this. They will be loaded in parallel without blocking
let _scenes: Vec<HandleUntyped> = asset_server.load_folder("models/monkey").unwrap();

Here is the function I wrote:

fn load_audio(mut commands: Commands, asset_server: Res<AssetServer>, audio: Res<Audio>) {
    let music = asset_server.load_folder("music").unwrap();
    for song in music {
        commands.spawn((
            Music,
            Sound(song),
        ));
    }
}

This code gives a compilation error because song is of the type HandleUntyped. My first idea was to convert HandleUntyped into Handle<AudioSource>. I have to imagine there is some way to do this, or else HanldeUntyped would be pretty useless, but looking through the Bevy docs I can't find any way to do this. Handle::<AudioSource>::from(song) didn't work. I've also considered using the std::fs library to get all the audio files in the directory and load them each individually with Bevy, but the existence of the load_folder method seems to imply that Bevy has a more elegant and simple way of doing this.

1

There are 1 answers

0
Denendaden On BEST ANSWER

Of course immediately after giving up the search and posting a question, I find the answer. HandleUntyped implements the typed() function, which converts it into a typed Handle. All I needed to do was replace Sound(song) with Sound(song.typed()).