From 33094e89f533c233d76c73649867e080544a8fef Mon Sep 17 00:00:00 2001 From: Wandalen Date: Fri, 14 Jan 2022 14:38:08 +0200 Subject: [PATCH] Add sample-based generation example: synth_tones (#612) --- Cargo.toml | 3 ++ examples/synth_tones.rs | 108 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 111 insertions(+) create mode 100644 examples/synth_tones.rs diff --git a/Cargo.toml b/Cargo.toml index 53d9a07..775c39b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -74,3 +74,6 @@ name = "feedback" [[example]] name = "record_wav" + +[[example]] +name = "synth_tones" diff --git a/examples/synth_tones.rs b/examples/synth_tones.rs new file mode 100644 index 0000000..d1fa5cb --- /dev/null +++ b/examples/synth_tones.rs @@ -0,0 +1,108 @@ +/* This example expose parameter to pass generator of sample. +Good starting point for integration of cpal into your application. +*/ + +extern crate anyhow; +extern crate clap; +extern crate cpal; + +use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; + +fn main() -> anyhow::Result<()> { + let stream = stream_setup_for(sample_next)?; + stream.play()?; + std::thread::sleep(std::time::Duration::from_millis(3000)); + Ok(()) +} + +fn sample_next(o: &mut SampleRequestOptions) -> f32 { + o.tick(); + o.tone(440.) * 0.1 + o.tone(880.) * 0.1 + // combination of several tones +} + +pub struct SampleRequestOptions { + pub sample_rate: f32, + pub sample_clock: f32, + pub nchannels: usize, +} + +impl SampleRequestOptions { + fn tone(&self, freq: f32) -> f32 { + (self.sample_clock * freq * 2.0 * std::f32::consts::PI / self.sample_rate).sin() + } + fn tick(&mut self) { + self.sample_clock = (self.sample_clock + 1.0) % self.sample_rate; + } +} + +pub fn stream_setup_for(on_sample: F) -> Result +where + F: FnMut(&mut SampleRequestOptions) -> f32 + std::marker::Send + 'static + Copy, +{ + let (_host, device, config) = host_device_setup()?; + + match config.sample_format() { + cpal::SampleFormat::F32 => stream_make::(&device, &config.into(), on_sample), + cpal::SampleFormat::I16 => stream_make::(&device, &config.into(), on_sample), + cpal::SampleFormat::U16 => stream_make::(&device, &config.into(), on_sample), + } +} + +pub fn host_device_setup( +) -> Result<(cpal::Host, cpal::Device, cpal::SupportedStreamConfig), anyhow::Error> { + let host = cpal::default_host(); + + let device = host + .default_output_device() + .ok_or_else(|| anyhow::Error::msg("Default output device is not available"))?; + println!("Output device : {}", device.name()?); + + let config = device.default_output_config()?; + println!("Default output config : {:?}", config); + + Ok((host, device, config)) +} + +pub fn stream_make( + device: &cpal::Device, + config: &cpal::StreamConfig, + on_sample: F, +) -> Result +where + T: cpal::Sample, + F: FnMut(&mut SampleRequestOptions) -> f32 + std::marker::Send + 'static + Copy, +{ + let sample_rate = config.sample_rate.0 as f32; + let sample_clock = 0f32; + let nchannels = config.channels as usize; + let mut request = SampleRequestOptions { + sample_rate, + sample_clock, + nchannels, + }; + let err_fn = |err| eprintln!("Error building output sound stream: {}", err); + + let stream = device.build_output_stream( + config, + move |output: &mut [T], _: &cpal::OutputCallbackInfo| { + on_window(output, &mut request, on_sample) + }, + err_fn, + )?; + + Ok(stream) +} + +fn on_window(output: &mut [T], request: &mut SampleRequestOptions, mut on_sample: F) +where + T: cpal::Sample, + F: FnMut(&mut SampleRequestOptions) -> f32 + std::marker::Send + 'static, +{ + for frame in output.chunks_mut(request.nchannels) { + let value: T = cpal::Sample::from::(&on_sample(request)); + for sample in frame.iter_mut() { + *sample = value; + } + } +}