The audio examples available show how to play a sound, once, immediately, and then look focused around music.
I want to load a series of sounds, then play them on demand. I do not want them constantly playing, I want them playing once then stopping.
What I've tried:
pub struct AudioPlugin;
pub struct Sfx;
#[derive(Event)]
pub struct PlaySound { pub sid: usize }
#[derive(Resource)]
pub struct AudioLibrary {
pub sounds: Vec<Handle<AudioSource>>,
}
impl Plugin for AudioPlugin {
fn build(&self, app: &mut App) {
app.add_event::<PlaySound>()
.insert_resource( AudioLibrary { sounds: Vec::with_capacity(50) } )
.add_systems(
OnEnter(GameState::InGame),
(init_audio, play_audio),
);
}
}
fn init_audio(
asset_server: Res<AssetServer>,
mut audio_library: ResMut<AudioLibrary>,
) {
let handle: Handle<AudioSource> = asset_server.load("sfx/stab1.wav");
audio_library.sounds.push(handle);
return;
}
fn play_audio(
mut events: EventReader<PlaySound>,
mut commands: Commands,
audio_library: Res<AudioLibrary>,
) {
for event in events.read() {
let sid = event.sid;
let handle = audio_library.sounds[sid];
commands.spawn(AudioPlayer::new(handle));
}
}
I get a borrow error because I cannot copy AudioSource:
error[E0507]: cannot move out of index of `std::vec::Vec<bevy::prelude::Handle<bevy::prelude::AudioSource>>`
--> src/audio.rs:45:18
|
45 | let handle = audio_library.sounds[sid];
| ^^^^^^^^^^^^^^^^^^^^^^^^^ move occurs because value has type `bevy::prelude::Handle<bevy::prelude::AudioSource>`, which does not implement the `Copy` trait
|
How can I load sounds and play them, later?