diff --git a/src/audio.rs b/src/audio.rs index 3e2ca7f..2341f1b 100644 --- a/src/audio.rs +++ b/src/audio.rs @@ -21,13 +21,17 @@ impl Plugin for AudioPlugin { ], }); + app.init_resource::(); app.add_systems(OnEnter(GameState::Menu), play_background); app.add_systems( Update, ( play_audio.run_if(any_component_added::), audio_trigger.run_if(on_event::()), - // play_background.run_if(on_event::>()), TODO: Handle music hot-reload + control_volume.run_if(resource_changed::()), + toggle_volume.run_if(|keys: Res>| -> bool { + keys.just_pressed(KeyCode::M) + }), ), ); } @@ -46,6 +50,15 @@ pub enum AudioEvent { Invalid, } +#[derive(Resource, Debug)] +pub struct AudioVolume(f32); + +impl Default for AudioVolume { + fn default() -> Self { + AudioVolume(1.0) + } +} + fn play_background(mut events: EventWriter) { events.send(AudioEvent::MainMusic); } @@ -62,6 +75,7 @@ fn audio_trigger( server: Res, tweaks: Res>, display_state: Res>, + vol: Res, ) { let tweak = tweaks .get(&server.load("martian.tweak.toml")) @@ -85,7 +99,6 @@ fn audio_trigger( if !aud.is_empty() { let event_str = format!("event:{}", aud); if let Ok(event_description) = studio.0.get_event(event_str.as_str()) { - let audio_source = AudioSource::new(event_description); // We are stopping a playing event match event { // Find and stop playing instances of idle audio @@ -113,6 +126,8 @@ fn audio_trigger( // we are playing a sound _ => { info!("Playing audio {}", event_str); + let audio_source = AudioSource::new(event_description); + audio_source.set_volume(vol.0); // TODO: Can we batch spawn all sounds at startup? Then Start/Stop/Reset at runtime? commands.spawn((audio_source, event.clone())); } @@ -123,3 +138,22 @@ fn audio_trigger( } }); } + +fn toggle_volume( + mut vol: ResMut, +) { + if vol.0 > 0.0 { + vol.0 = 0.0; + } else { + vol.0 = 1.0; + } +} + +fn control_volume( + vol: Res, + query: Query<&AudioSource>, +) { + query.iter().for_each(|aud_src| { + aud_src.set_volume((*vol).0) + }); +} \ No newline at end of file