Skip to content

Commit

Permalink
Add a couple more rust + sdl2-audio samples
Browse files Browse the repository at this point in the history
  • Loading branch information
piki committed Jan 29, 2024
1 parent f21e522 commit 1613d2e
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/bin/play-wav.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use std::env;

use sdl2::audio::{AudioSpecDesired, AudioSpecWAV};
use std::time::Duration;

fn main() {
let args: Vec<String> = 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));
}
}
52 changes: 52 additions & 0 deletions src/bin/square-wave.rs
Original file line number Diff line number Diff line change
@@ -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));
}

0 comments on commit 1613d2e

Please sign in to comment.