mirror of
https://github.com/encounter/rust-sdl2.git
synced 2026-03-30 11:37:10 -07:00
60 lines
1.3 KiB
Rust
60 lines
1.3 KiB
Rust
extern crate sdl2;
|
|
|
|
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() -> Result<(), String> {
|
|
let sdl_context = sdl2::init()?;
|
|
let audio_subsystem = sdl_context.audio()?;
|
|
|
|
let desired_spec = AudioSpecDesired {
|
|
freq: Some(44_100),
|
|
channels: Some(1), // mono
|
|
samples: None, // default sample size
|
|
};
|
|
|
|
let device = audio_subsystem.open_playback(None, &desired_spec, |spec| {
|
|
// Show obtained AudioSpec
|
|
println!("{:?}", spec);
|
|
|
|
// initialize the audio callback
|
|
SquareWave {
|
|
phase_inc: 440.0 / spec.freq as f32,
|
|
phase: 0.0,
|
|
volume: 0.25,
|
|
}
|
|
})?;
|
|
|
|
// Start playback
|
|
device.resume();
|
|
|
|
// Play for 2 seconds
|
|
std::thread::sleep(Duration::from_millis(2_000));
|
|
|
|
// Device is automatically closed when dropped
|
|
|
|
Ok(())
|
|
}
|