cpal/examples/beep.rs

56 lines
1.8 KiB
Rust
Raw Normal View History

2014-12-11 15:28:26 +00:00
extern crate cpal;
2016-09-30 16:18:28 +00:00
2014-12-11 15:28:26 +00:00
fn main() {
let endpoint = cpal::default_endpoint().expect("Failed to get default endpoint");
2017-10-11 11:24:49 +00:00
let format = endpoint
.supported_formats()
.unwrap()
.next()
2017-10-20 19:18:40 +00:00
.expect("Failed to get endpoint format")
.with_max_sample_rate();
2016-08-02 14:13:59 +00:00
let event_loop = cpal::EventLoop::new();
let voice_id = event_loop.build_voice(&endpoint, &format).unwrap();
event_loop.play(voice_id);
2014-12-11 16:23:33 +00:00
let sample_rate = format.sample_rate.0 as f32;
let mut sample_clock = 0f32;
// Produce a sinusoid of maximum amplitude.
let mut next_value = || {
sample_clock = (sample_clock + 1.0) % sample_rate;
(sample_clock * 440.0 * 2.0 * 3.141592 / sample_rate).sin()
};
event_loop.run(move |_, buffer| {
2016-08-02 14:13:59 +00:00
match buffer {
2015-08-20 12:38:25 +00:00
cpal::UnknownTypeBuffer::U16(mut buffer) => {
for sample in buffer.chunks_mut(format.channels as usize) {
let value = ((next_value() * 0.5 + 0.5) * std::u16::MAX as f32) as u16;
2017-10-11 11:24:49 +00:00
for out in sample.iter_mut() {
*out = value;
}
2015-08-20 12:38:25 +00:00
}
},
2015-08-20 12:38:25 +00:00
cpal::UnknownTypeBuffer::I16(mut buffer) => {
for sample in buffer.chunks_mut(format.channels as usize) {
let value = (next_value() * std::i16::MAX as f32) as i16;
2017-10-11 11:24:49 +00:00
for out in sample.iter_mut() {
*out = value;
}
2015-08-20 12:38:25 +00:00
}
},
cpal::UnknownTypeBuffer::F32(mut buffer) => {
for sample in buffer.chunks_mut(format.channels as usize) {
let value = next_value();
2017-10-11 11:24:49 +00:00
for out in sample.iter_mut() {
*out = value;
}
2015-08-20 12:38:25 +00:00
}
},
2016-08-02 14:13:59 +00:00
};
});
2014-12-11 15:28:26 +00:00
}