From e7a261ce367cee23c4d25d607e0c774823032e05 Mon Sep 17 00:00:00 2001 From: Elijah Voigt Date: Thu, 28 Sep 2023 20:29:04 -0700 Subject: [PATCH] Dynamic audio picking --- examples/hello-fmod.rs | 50 +++++++++++++++++++++++++++++------------- 1 file changed, 35 insertions(+), 15 deletions(-) diff --git a/examples/hello-fmod.rs b/examples/hello-fmod.rs index ae4e333..02ddf5f 100644 --- a/examples/hello-fmod.rs +++ b/examples/hello-fmod.rs @@ -1,6 +1,8 @@ //! This example demonstrates how to use the FmodPlugin to play a sound. //! Make sure to follow the instructions in the README.md to set up the demo project. +use bevy::input::keyboard::KeyboardInput; +use bevy::input::ButtonState; use bevy::prelude::*; use bevy_fmod::prelude::AudioSource; use bevy_fmod::prelude::*; @@ -19,6 +21,7 @@ fn main() { )) .add_systems(Startup, startup) .add_systems(PostStartup, play_music) + .add_systems(Update, set_music) .run(); } @@ -55,20 +58,37 @@ fn startup(mut commands: Commands, studio: Res) { fn play_music(mut audio_sources: Query<&AudioSource, With>) { if let Ok(audio_source) = audio_sources.get_single_mut() { audio_source.play(); - - info!( - "Parameter by name: {:?}", - audio_source - .event_instance - .get_parameter_by_name("Game State") - .expect("Get parameter") - ); - match audio_source - .event_instance - .set_parameter_by_name("Game State", 5.0, true) - { - Ok(_) => (), - Err(e) => warn!("Error: {:?}", e), - }; } } + +fn set_music( + mut events: EventReader, + mut audio_sources: Query<&AudioSource, With>, +) { + events.iter().for_each( + |KeyboardInput { + key_code, state, .. + }| { + if let Ok(audio_source) = audio_sources.get_single_mut() { + let target = match state { + ButtonState::Pressed => match key_code { + Some(KeyCode::Key1) => 0.0, + Some(KeyCode::Key2) => 1.0, + Some(KeyCode::Key3) => 2.0, + Some(KeyCode::Key4) => 3.0, + Some(KeyCode::Key5) => 4.0, + Some(KeyCode::Key6) => 5.0, + _ => -1.0, + }, + _ => -1.0, + }; + if target >= 0.0 { + audio_source + .event_instance + .set_parameter_by_name("Game State", target, true) + .expect("Set audio parameter"); + } + } + }, + ); +}