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() {
|
2018-02-12 13:10:24 +00:00
|
|
|
let device = cpal::default_output_device().expect("Failed to get default output device");
|
|
|
|
let format = device.default_output_format().expect("Failed to get default output format");
|
2016-08-02 14:13:59 +00:00
|
|
|
let event_loop = cpal::EventLoop::new();
|
2018-02-12 13:10:24 +00:00
|
|
|
let stream_id = event_loop.build_output_stream(&device, &format).unwrap();
|
2019-06-21 01:03:03 +00:00
|
|
|
event_loop.play_stream(stream_id.clone()).unwrap();
|
2014-12-11 16:23:33 +00:00
|
|
|
|
2018-02-04 12:02:16 +00:00
|
|
|
let sample_rate = format.sample_rate.0 as f32;
|
2017-10-20 15:12:01 +00:00
|
|
|
let mut sample_clock = 0f32;
|
|
|
|
|
|
|
|
// Produce a sinusoid of maximum amplitude.
|
|
|
|
let mut next_value = || {
|
2018-02-04 12:02:16 +00:00
|
|
|
sample_clock = (sample_clock + 1.0) % sample_rate;
|
|
|
|
(sample_clock * 440.0 * 2.0 * 3.141592 / sample_rate).sin()
|
2017-10-20 15:12:01 +00:00
|
|
|
};
|
2014-12-11 16:51:58 +00:00
|
|
|
|
2018-02-12 13:10:24 +00:00
|
|
|
event_loop.run(move |_, data| {
|
|
|
|
match data {
|
|
|
|
cpal::StreamData::Output { buffer: cpal::UnknownTypeOutputBuffer::U16(mut buffer) } => {
|
2018-02-04 09:38:06 +00:00
|
|
|
for sample in buffer.chunks_mut(format.channels as usize) {
|
2017-10-20 15:12:01 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
},
|
2018-02-12 13:10:24 +00:00
|
|
|
cpal::StreamData::Output { buffer: cpal::UnknownTypeOutputBuffer::I16(mut buffer) } => {
|
2018-02-04 09:38:06 +00:00
|
|
|
for sample in buffer.chunks_mut(format.channels as usize) {
|
2017-10-20 15:12:01 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
},
|
2018-02-12 13:10:24 +00:00
|
|
|
cpal::StreamData::Output { buffer: cpal::UnknownTypeOutputBuffer::F32(mut buffer) } => {
|
2018-02-04 09:38:06 +00:00
|
|
|
for sample in buffer.chunks_mut(format.channels as usize) {
|
2017-10-20 15:12:01 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
},
|
2018-02-12 13:10:24 +00:00
|
|
|
_ => (),
|
|
|
|
}
|
2017-10-18 18:24:05 +00:00
|
|
|
});
|
2014-12-11 15:28:26 +00:00
|
|
|
}
|