Files

59 lines
1.3 KiB
Rust
Raw Permalink Normal View History

2015-04-04 23:04:24 -06:00
extern crate sdl2;
2015-07-26 07:15:44 -06:00
use sdl2::audio::{AudioCallback, AudioSpecDesired};
use std::time::Duration;
2015-04-04 23:04:24 -06:00
struct SquareWave {
phase_inc: f32,
phase: f32,
2020-12-08 17:06:23 +01:00
volume: f32,
2015-04-04 23:04:24 -06:00
}
impl AudioCallback for SquareWave {
type Channel = f32;
fn callback(&mut self, out: &mut [f32]) {
// Generate a square wave
for x in out.iter_mut() {
2020-12-08 17:06:23 +01:00
*x = if self.phase <= 0.5 {
self.volume
} else {
-self.volume
};
2015-04-04 23:04:24 -06:00
self.phase = (self.phase + self.phase_inc) % 1.0;
}
}
}
fn main() -> Result<(), String> {
let sdl_context = sdl2::init()?;
let audio_subsystem = sdl_context.audio()?;
2015-04-04 23:04:24 -06:00
let desired_spec = AudioSpecDesired {
2017-08-23 18:56:12 +02:00
freq: Some(44_100),
2020-12-08 17:06:23 +01:00
channels: Some(1), // mono
samples: None, // default sample size
2015-04-04 23:04:24 -06:00
};
2016-01-23 23:01:16 +01:00
let device = audio_subsystem.open_playback(None, &desired_spec, |spec| {
2015-04-04 23:04:24 -06:00
// Show obtained AudioSpec
println!("{:?}", spec);
// initialize the audio callback
SquareWave {
phase_inc: 440.0 / spec.freq as f32,
phase: 0.0,
2020-12-08 17:06:23 +01:00
volume: 0.25,
2015-04-04 23:04:24 -06:00
}
})?;
2015-04-04 23:04:24 -06:00
// Start playback
device.resume();
// Play for 2 seconds
2017-08-23 18:56:12 +02:00
std::thread::sleep(Duration::from_millis(2_000));
2015-04-04 23:04:24 -06:00
// Device is automatically closed when dropped
2020-12-08 17:06:23 +01:00
Ok(())
2015-04-04 23:04:24 -06:00
}