-
Hi, I am just doing a bevy 0.10 tutorial and adapt it to 0.11 on the fly. How would I do something like this in an ECS idiomatic way with the new 0.11 Audio system? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Playing an audio clip in Bevy 0.11 is as easy as spawning an Here's some code similar to the YouTube video: fn play_sound(mut commands: Commands, asset_server: Res<AssetServer>) {
let sound = if random::<f32>() > 0.5 {
asset_server.load("one.ogg")
} else {
asset_server.load("two.ogg")
};
commands.spawn(AudioBundle {
source: sound,
// auto-despawn the entity when playback finishes
settings: PlaybackSettings::DESPAWN,
});
} There is one slight problem with this code: The audio files may be unloaded and their handles cleaned up by the asset server. This won't prevent things from working, but your app might have to do extra work when playing sounds which could introduce latency. You can store their handles in a // Be sure to initialize this resource when building your app in `fn main`
// with `.init_resource::<SoundHandles>`.
#[derive(Resource)]
struct SoundHandles {
one: Handle<AudioSource>,
two: Handle<AudioSource>,
}
impl FromWorld for SoundHandles {
fn from_world(world: &mut World) -> Self {
let asset_server = world.resource::<AssetServer>();
Self {
one: asset_server.load("audio/one.ogg"),
two: asset_server.load("audio/two.ogg"),
}
}
}
fn play_sound(mut commands: Commands, handles: Res<SoundHandles>) {
// Also, `random` is generic and will produce a `bool` that is `true` 50% of the time if used in this context.
let sound = if random() {
handles.one.clone()
} else {
handles.two.clone()
};
commands.spawn(AudioBundle {
source: sound,
// auto-despawn the entity when playback finishes
settings: PlaybackSettings::DESPAWN,
});
} |
Beta Was this translation helpful? Give feedback.
Playing an audio clip in Bevy 0.11 is as easy as spawning an
AudioBundle
.Here's some code similar to the YouTube video:
There is one slight problem with this code: The audio files may be unloaded and their handles cleaned up by the asset server. This won't prevent things from working, but your app might have to do e…