From 1613d2e4983d105770813bf46c3c29c744de3ab9 Mon Sep 17 00:00:00 2001 From: Patrick Reynolds Date: Sun, 28 Jan 2024 21:02:10 -0500 Subject: [PATCH] Add a couple more rust + sdl2-audio samples --- src/bin/play-wav.rs | 31 +++++++++++++++++++++++++ src/bin/square-wave.rs | 52 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 src/bin/play-wav.rs create mode 100644 src/bin/square-wave.rs diff --git a/src/bin/play-wav.rs b/src/bin/play-wav.rs new file mode 100644 index 0000000..af18ac1 --- /dev/null +++ b/src/bin/play-wav.rs @@ -0,0 +1,31 @@ +use std::env; + +use sdl2::audio::{AudioSpecDesired, AudioSpecWAV}; +use std::time::Duration; + +fn main() { + let args: Vec = env::args().collect(); + if args.len() < 2 { + println!("Usage:"); + println!(" {} foo.wav...", args[0]); + return; + } + let sdl = sdl2::init().unwrap(); + let sounds: Vec<_> = args[1..].iter().map(|f| + AudioSpecWAV::load_wav(f).unwrap() + ).collect(); + for sound in sounds { + let audio_len = sound.buffer().len(); // bytes + dbg!(&audio_len); + let desired = AudioSpecDesired{ + freq: Some(sound.freq), + channels: Some(sound.channels), + samples: Some(sound.format as u16) + }; + let audio = sdl.audio().unwrap(); + let sound_queue = audio.open_queue(None, &desired).unwrap(); + sound_queue.queue_audio(sound.buffer()).unwrap(); + sound_queue.resume(); + std::thread::sleep(Duration::from_millis(audio_len as u64 * 1000 / sound.freq as u64 / sound.channels as u64)); + } +} diff --git a/src/bin/square-wave.rs b/src/bin/square-wave.rs new file mode 100644 index 0000000..6635d1d --- /dev/null +++ b/src/bin/square-wave.rs @@ -0,0 +1,52 @@ +use sdl2::audio::{AudioCallback, AudioSpecDesired}; +use std::time::Duration; + +struct SquareWave { + phase_inc: f32, + phase: f32, + volume: f32, +} + +impl AudioCallback for SquareWave { + type Channel = f32; + + fn callback(&mut self, out: &mut [f32]) { + // Generate a square wave + for x in out.iter_mut() { + *x = if self.phase <= 0.5 { + self.volume + } else { + -self.volume + }; + self.phase = (self.phase + self.phase_inc) % 1.0; + } + } +} + +fn main() { + let sdl_context = sdl2::init().unwrap(); + let audio_subsystem = sdl_context.audio().unwrap(); + + let desired_spec = AudioSpecDesired { + freq: Some(44100), + channels: Some(1), // mono + samples: None, // default sample size + }; + + let device = audio_subsystem + .open_playback(None, &desired_spec, |spec| { + // initialize the audio callback + SquareWave { + phase_inc: 440.0 / spec.freq as f32, + phase: 0.0, + volume: 0.25, + } + }) + .unwrap(); + + // Start playback + device.resume(); + + // Play for 2 seconds + std::thread::sleep(Duration::from_millis(2000)); +}