outfly/src/audio.rs

88 lines
2.3 KiB
Rust
Raw Normal View History

2024-03-16 19:53:57 +00:00
use bevy::prelude::*;
2024-03-16 23:41:06 +00:00
use bevy::audio::PlaybackMode;
2024-03-16 19:53:57 +00:00
2024-03-17 23:04:23 +00:00
pub struct AudioPlugin;
impl Plugin for AudioPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, setup);
app.add_systems(Update, toggle_bgm);
2024-03-18 00:52:41 +00:00
app.add_systems(PostUpdate, play_click);
app.add_event::<AudioClickEvent>();
2024-03-17 23:04:23 +00:00
}
}
2024-03-18 00:52:41 +00:00
#[derive(Event)]
pub struct AudioClickEvent();
2024-03-16 19:53:57 +00:00
#[derive(Component)]
pub struct ComponentBGM;
2024-03-16 23:41:06 +00:00
#[derive(Component)]
pub struct ComponentThrusterSound;
2024-03-16 19:53:57 +00:00
#[derive(Resource)]
struct SoundBGM(Handle<AudioSource>);
2024-03-18 00:52:41 +00:00
#[derive(Resource)]
pub struct SoundClick(Handle<AudioSource>);
2024-03-16 19:53:57 +00:00
pub fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
) {
let bgm = SoundBGM(asset_server.load("tmp/FTL - Faster Than Light (2012) OST - 12 - Void (Explore)-edQw2yYXQJM.ogg"));
2024-03-16 19:53:57 +00:00
commands.spawn((
AudioBundle {
source: bgm.0.clone(),
settings: PlaybackSettings::LOOP,
},
ComponentBGM,
));
commands.insert_resource(bgm);
commands.spawn((
AudioBundle {
source: asset_server.load("sounds/wakeup.ogg"),
settings: PlaybackSettings::DESPAWN,
},
));
2024-03-16 23:41:06 +00:00
commands.spawn((
ComponentThrusterSound,
AudioBundle {
source: asset_server.load("tmp/loopingthrust-95548.ogg"),
2024-03-16 23:41:06 +00:00
settings: PlaybackSettings {
mode: PlaybackMode::Loop,
paused: true,
..default()
},
},
));
2024-03-18 00:52:41 +00:00
let click_sound_handle = asset_server.load("tmp/analog-appliance-button-1-185276.ogg");
commands.insert_resource(SoundClick(click_sound_handle));
2024-03-16 19:53:57 +00:00
}
pub fn toggle_bgm(
keyboard_input: Res<ButtonInput<KeyCode>>,
bgm_controller: Query<&AudioSink, With<ComponentBGM>>,
) {
if keyboard_input.just_pressed(KeyCode::KeyT) {
if let Ok(sink) = bgm_controller.get_single() {
sink.toggle()
}
}
}
2024-03-18 00:52:41 +00:00
pub fn play_click(
mut commands: Commands,
mut events: EventReader<AudioClickEvent>,
sound: Res<SoundClick>,
) {
if !events.is_empty() {
events.clear();
commands.spawn(AudioBundle {
source: sound.0.clone(),
// auto-despawn the entity when playback finishes
settings: PlaybackSettings::DESPAWN,
});
}
}