From 20d0d8630df1b9cbcf76c271d56a2040b59b02ea Mon Sep 17 00:00:00 2001 From: gered Date: Sun, 5 Jun 2022 18:42:09 -0400 Subject: [PATCH] add global audio volume control --- examples/audio_playback/src/main.rs | 15 +++++++++++++-- libretrogd/src/audio/mod.rs | 8 +++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/examples/audio_playback/src/main.rs b/examples/audio_playback/src/main.rs index ee0b28d..0a1658a 100644 --- a/examples/audio_playback/src/main.rs +++ b/examples/audio_playback/src/main.rs @@ -58,6 +58,7 @@ fn main() -> Result<()> { let mut system = SystemBuilder::new().window_title("Audio Playback").vsync(true).build()?; let mut is_running = true; + let mut volume = 1.0; let sounds = [ load_and_convert_wav(Path::new("./assets/pickup-coin.wav"), system.audio.spec())?, @@ -77,6 +78,7 @@ fn main() -> Result<()> { }); let mut audio_device = system.audio.lock(); + audio_device.volume = volume; if system.keyboard.is_key_pressed(Scancode::Escape) { is_running = false; @@ -111,6 +113,13 @@ fn main() -> Result<()> { audio_device.play_buffer_on_channel(7, &sounds[index], false)?; } + if system.keyboard.is_key_pressed(Scancode::KpMinus) { + volume -= 0.1; + } + if system.keyboard.is_key_pressed(Scancode::KpPlus) { + volume += 0.1; + } + for index in 0..NUM_CHANNELS { let channel = &audio_device[index]; let mut status = &mut statuses[index]; @@ -123,9 +132,11 @@ fn main() -> Result<()> { system.video.clear(0); - system.video.print_string("Audio Channels", 16, 16, FontRenderOpts::Color(14), &system.font); + system.video.print_string(&format!("Volume: {:2.2}", volume), 16, 16, FontRenderOpts::Color(10), &system.font); - let mut y = 32; + system.video.print_string("Audio Channels", 16, 32, FontRenderOpts::Color(14), &system.font); + + let mut y = 48; for index in 0..NUM_CHANNELS { let status = &statuses[index]; system.video.print_string( diff --git a/libretrogd/src/audio/mod.rs b/libretrogd/src/audio/mod.rs index 8e3cbba..6186125 100644 --- a/libretrogd/src/audio/mod.rs +++ b/libretrogd/src/audio/mod.rs @@ -196,6 +196,7 @@ pub enum AudioDeviceError { pub struct AudioDevice { spec: AudioSpec, channels: Vec, + pub volume: f32, } impl AudioCallback for AudioDevice { @@ -209,6 +210,7 @@ impl AudioCallback for AudioDevice { sample += this_sample; } } + sample = ((sample as f32) * self.volume) as i16; *dest = (sample.clamp(-128, 127) + 128) as u8; } } @@ -220,7 +222,11 @@ impl AudioDevice { for _ in 0..NUM_CHANNELS { channels.push(AudioChannel::new()); } - AudioDevice { spec, channels } + AudioDevice { + spec, + channels, + volume: 1.0, + } } #[inline]