move audio code to separate file

This commit is contained in:
yuni 2024-03-16 20:53:57 +01:00
parent e0c1b2cfb8
commit 7a39938efb
2 changed files with 47 additions and 30 deletions

39
src/audio.rs Normal file
View file

@ -0,0 +1,39 @@
use bevy::prelude::*;
#[derive(Component)]
pub struct ComponentBGM;
#[derive(Resource)]
struct SoundBGM(Handle<AudioSource>);
pub fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
) {
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<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()
}
}
}

View file

@ -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<AudioSource>);
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<ButtonInput<KeyCode>>,
bgm_controller: Query<&AudioSink, With<ComponentBGM>>,
mut app_exit_events: ResMut<Events<bevy::app::AppExit>>
) {
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);
}