Skip to content

Commit 939c07c

Browse files
committed
[add] example audio sine wave example.
1 parent 59c548c commit 939c07c

1 file changed

Lines changed: 78 additions & 0 deletions

File tree

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#![allow(clippy::needless_return)]
2+
//! Audio output example that plays a short sine wave tone.
3+
//!
4+
//! This example is application-facing and uses only the `lambda-rs` API surface.
5+
6+
#[cfg(feature = "audio-output-device")]
7+
use std::{
8+
thread,
9+
time::Duration,
10+
};
11+
12+
#[cfg(feature = "audio-output-device")]
13+
use lambda::audio::{
14+
enumerate_output_devices,
15+
AudioOutputDeviceBuilder,
16+
};
17+
18+
#[cfg(not(feature = "audio-output-device"))]
19+
fn main() {
20+
eprintln!(
21+
"This example requires `lambda-rs` feature `audio-output-device`.\n\n\
22+
Run:\n cargo run -p lambda-rs --example audio_sine_wave --features audio-output-device"
23+
);
24+
}
25+
26+
#[cfg(feature = "audio-output-device")]
27+
fn main() {
28+
let devices = match enumerate_output_devices() {
29+
Ok(devices) => devices,
30+
Err(error) => {
31+
eprintln!("Failed to enumerate audio output devices: {error:?}");
32+
return;
33+
}
34+
};
35+
36+
println!("Available output devices:");
37+
for device in devices {
38+
let default_marker = if device.is_default { " (default)" } else { "" };
39+
println!(" - {}{default_marker}", device.name);
40+
}
41+
42+
let frequency_hz = 440.0f32;
43+
let amplitude = 0.10f32;
44+
let mut phase_radians = 0.0f32;
45+
46+
let device = AudioOutputDeviceBuilder::new()
47+
.with_label("audio_sine_wave")
48+
.build_with_output_callback(move |writer, callback_info| {
49+
let phase_delta = std::f32::consts::TAU * frequency_hz
50+
/ (callback_info.sample_rate as f32);
51+
52+
for frame_index in 0..writer.frames() {
53+
let sample = (phase_radians.sin()) * amplitude;
54+
for channel_index in 0..(writer.channels() as usize) {
55+
writer.set_sample(frame_index, channel_index, sample);
56+
}
57+
58+
phase_radians += phase_delta;
59+
if phase_radians > std::f32::consts::TAU {
60+
phase_radians -= std::f32::consts::TAU;
61+
}
62+
}
63+
64+
return;
65+
});
66+
67+
let _device = match device {
68+
Ok(device) => device,
69+
Err(error) => {
70+
eprintln!("Failed to initialize audio output device: {error:?}");
71+
return;
72+
}
73+
};
74+
75+
println!("Playing 440 Hz sine wave for 2 seconds...");
76+
thread::sleep(Duration::from_secs(2));
77+
println!("Done.");
78+
}

0 commit comments

Comments
 (0)