docs/bevy/examples/audio/play_sound_effect.rs 1.5 K · 56 lines · raw · history

1 //! This example illustrates how to play a sound effect on an event.
2 //! In this case, we will play a sound effect when the space key is pressed.
3 use bevy::prelude::*;
4
5 #[derive(Resource, Deref)]
6 struct SoundEffect {
7 handle: Handle<AudioSource>,
8 }
9
10 // We can setup the logic for how to load our assets in the `FromWorld` trait.
11 // This code is called via `init_resource`.
12 impl FromWorld for SoundEffect {
13 fn from_world(world: &mut World) -> Self {
14 let asset_server = world.resource::<AssetServer>();
15 SoundEffect {
16 handle: asset_server.load("sounds/breakout_collision.ogg"),
17 }
18 }
19 }
20
21 fn main() {
22 App::new()
23 .add_plugins(DefaultPlugins)
24 .init_resource::<SoundEffect>()
25 .add_systems(Startup, setup)
26 .add_systems(Update, keyboard_event)
27 .run();
28 }
29
30 fn setup(mut commands: Commands) {
31 commands.spawn(Camera2d);
32 // example instruction
33 commands.spawn((
34 Text::new("Press Space to play the sound effect."),
35 Node {
36 position_type: PositionType::Absolute,
37 bottom: px(12),
38 left: px(12),
39 ..default()
40 },
41 ));
42 }
43
44 // spawn an audio player with the sound effect when the space key is pressed
45 fn keyboard_event(
46 keyboard_input: Res<ButtonInput<KeyCode>>,
47 sound_effect: Res<SoundEffect>,
48 mut commands: Commands,
49 ) {
50 if keyboard_input.just_pressed(KeyCode::Space) {
51 commands.spawn((
52 AudioPlayer::new(sound_effect.clone()),
53 PlaybackSettings::DESPAWN,
54 ));
55 }
56 }