From 7a39938efb1d781cdf3b993ebe375863b7e8a64f Mon Sep 17 00:00:00 2001 From: hut Date: Sat, 16 Mar 2024 20:53:57 +0100 Subject: [PATCH] move audio code to separate file --- src/audio.rs | 39 +++++++++++++++++++++++++++++++++++++++ src/main.rs | 38 ++++++++------------------------------ 2 files changed, 47 insertions(+), 30 deletions(-) create mode 100644 src/audio.rs diff --git a/src/audio.rs b/src/audio.rs new file mode 100644 index 0000000..9159d19 --- /dev/null +++ b/src/audio.rs @@ -0,0 +1,39 @@ +use bevy::prelude::*; + +#[derive(Component)] +pub struct ComponentBGM; + +#[derive(Resource)] +struct SoundBGM(Handle); + +pub fn setup( + mut commands: Commands, + asset_server: Res, +) { + let bgm = SoundBGM(asset_server.load("restricted/FTL - Faster Than Light (2012) OST - 12 - Void (Explore)-edQw2yYXQJM.ogg")); + 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, + }, + )); +} + +pub fn toggle_bgm( + keyboard_input: Res>, + bgm_controller: Query<&AudioSink, With>, +) { + if keyboard_input.just_pressed(KeyCode::KeyT) { + if let Ok(sink) = bgm_controller.get_single() { + sink.toggle() + } + } +} diff --git a/src/main.rs b/src/main.rs index 0d0ab6e..95baade 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,5 @@ +mod audio; + use bevy::{ asset::LoadState, window::{ @@ -16,10 +18,14 @@ use bevy::{ fn main() { App::new() - .add_systems(Startup, setup) + .add_systems(Startup, ( + setup, + audio::setup, + )) .add_systems(Update, ( asset_loaded.after(load_cubemap_asset), - handle_input + handle_input, + audio::toggle_bgm, )) .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest())) .add_plugins(CameraControllerPlugin) @@ -40,11 +46,6 @@ const CUBEMAPS: &[(&str, CompressedImageFormats)] = &[ ), ]; -#[derive(Component)] -struct ComponentBGM; -#[derive(Resource)] -struct SoundBGM(Handle); - fn setup( mut commands: Commands, @@ -58,23 +59,6 @@ fn setup( window.mode = WindowMode::Fullscreen; } - // Sound - let bgm = SoundBGM(asset_server.load("restricted/FTL - Faster Than Light (2012) OST - 12 - Void (Explore)-edQw2yYXQJM.ogg")); - 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, - }, - )); - // camera commands.spawn(( Camera3dBundle { @@ -151,14 +135,8 @@ fn asset_loaded( fn handle_input( keyboard_input: Res>, - bgm_controller: Query<&AudioSink, With>, mut app_exit_events: ResMut> ) { - if keyboard_input.just_pressed(KeyCode::KeyT) { - if let Ok(sink) = bgm_controller.get_single() { - sink.toggle() - } - } if keyboard_input.pressed(KeyCode::KeyQ) { app_exit_events.send(bevy::app::AppExit); }