cpal/examples/beep.rs

91 lines
2.7 KiB
Rust
Raw Normal View History

2014-12-11 15:28:26 +00:00
extern crate cpal;
2016-08-02 14:13:59 +00:00
extern crate futures;
use futures::stream::Stream;
2016-09-30 16:18:28 +00:00
use futures::task;
use futures::task::Executor;
use futures::task::Run;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
2016-09-30 16:18:28 +00:00
struct MyExecutor;
impl Executor for MyExecutor {
fn execute(&self, r: Run) {
r.run();
}
}
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()
.expect("Failed to get endpoint format");
2016-08-02 14:13:59 +00:00
let event_loop = cpal::EventLoop::new();
2016-09-30 16:18:28 +00:00
let executor = Arc::new(MyExecutor);
2016-08-02 14:13:59 +00:00
2017-10-11 11:24:49 +00:00
let (mut voice, stream) = cpal::Voice::new(&endpoint, &format, &event_loop)
.expect("Failed to create a voice");
2014-12-11 16:23:33 +00:00
2015-04-27 15:33:02 +00:00
// Produce a sinusoid of maximum amplitude.
2016-08-02 14:13:59 +00:00
let samples_rate = format.samples_rate.0 as f32;
let mut data_source = (0u64..).map(move |t| t as f32 * 440.0 * 2.0 * 3.141592 / samples_rate) // 440 Hz
.map(move |t| t.sin());
2016-08-02 14:13:59 +00:00
voice.play();
2016-09-30 16:18:28 +00:00
task::spawn(stream.for_each(move |buffer| -> Result<_, ()> {
2016-08-02 14:13:59 +00:00
match buffer {
2015-08-20 12:38:25 +00:00
cpal::UnknownTypeBuffer::U16(mut buffer) => {
2017-10-11 11:24:49 +00:00
for (sample, value) in buffer
.chunks_mut(format.channels.len())
.zip(&mut data_source)
{
2015-08-20 12:38:25 +00:00
let value = ((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) => {
2017-10-11 11:24:49 +00:00
for (sample, value) in buffer
.chunks_mut(format.channels.len())
.zip(&mut data_source)
{
2015-08-20 12:38:25 +00:00
let value = (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) => {
2017-10-11 11:24:49 +00:00
for (sample, value) in buffer
.chunks_mut(format.channels.len())
.zip(&mut data_source)
{
for out in sample.iter_mut() {
*out = value;
}
2015-08-20 12:38:25 +00:00
}
},
2016-08-02 14:13:59 +00:00
};
Ok(())
2016-09-30 16:18:28 +00:00
})).execute(executor);
2014-12-22 13:16:47 +00:00
2017-10-11 11:24:49 +00:00
thread::spawn(move || loop {
thread::sleep(Duration::from_millis(500));
voice.pause();
thread::sleep(Duration::from_millis(500));
voice.play();
});
2016-08-02 14:13:59 +00:00
event_loop.run();
2014-12-11 15:28:26 +00:00
}