From fc043c96a60e99b07ea8e7a42447b333a7dd2e1c Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Wed, 11 Sep 2019 02:40:06 -0400 Subject: [PATCH] add cpal example --- Cargo.lock | 1 + Cargo.toml | 1 + examples/record_wav.rs | 111 +++++++++++++++++++++++++++++++++++++++++ src/main.rs | 10 ++++ 4 files changed, 123 insertions(+) create mode 100644 examples/record_wav.rs diff --git a/Cargo.lock b/Cargo.lock index f2e2280e68..4dd3da4463 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -536,6 +536,7 @@ name = "voder" version = "0.0.0" dependencies = [ "cpal 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)", + "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", "hound 3.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "sample 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)", "sonogram 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", diff --git a/Cargo.toml b/Cargo.toml index cafd71b248..78c6309ac6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ name = "voder" [dependencies] cpal = "0.10.0" # hardware audio out +failure = "0.1.5" # required by cpal hound = "3.4.0" # wav encoder/decoder sample = "0.10.0" # DSP toolkit sonogram = "0.3.0" # badass spectrograms diff --git a/examples/record_wav.rs b/examples/record_wav.rs new file mode 100644 index 0000000000..cf74d38bf9 --- /dev/null +++ b/examples/record_wav.rs @@ -0,0 +1,111 @@ +//! NB: FROM CPAL LIBRARY +//! +//! Records a WAV file (roughly 3 seconds long) using the default input device and format. +//! +//! The input data is recorded to "$CARGO_MANIFEST_DIR/recorded.wav". + +extern crate cpal; +extern crate failure; +extern crate hound; + +use cpal::traits::{DeviceTrait, EventLoopTrait, HostTrait}; + +fn main() -> Result<(), failure::Error> { + // Use the default host for working with audio devices. + let host = cpal::default_host(); + + // Setup the default input device and stream with the default input format. + let device = host.default_input_device().expect("Failed to get default input device"); + println!("Default input device: {}", device.name()?); + let format = device.default_input_format().expect("Failed to get default input format"); + println!("Default input format: {:?}", format); + let event_loop = host.event_loop(); + let stream_id = event_loop.build_input_stream(&device, &format)?; + event_loop.play_stream(stream_id)?; + + // The WAV file we're recording to. + const PATH: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/recorded.wav"); + let spec = wav_spec_from_format(&format); + let writer = hound::WavWriter::create(PATH, spec)?; + let writer = std::sync::Arc::new(std::sync::Mutex::new(Some(writer))); + + // A flag to indicate that recording is in progress. + println!("Begin recording..."); + let recording = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); + + // Run the input stream on a separate thread. + let writer_2 = writer.clone(); + let recording_2 = recording.clone(); + std::thread::spawn(move || { + event_loop.run(move |id, event| { + let data = match event { + Ok(data) => data, + Err(err) => { + eprintln!("an error occurred on stream {:?}: {}", id, err); + return; + } + }; + + // If we're done recording, return early. + if !recording_2.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + // Otherwise write to the wav writer. + match data { + cpal::StreamData::Input { buffer: cpal::UnknownTypeInputBuffer::U16(buffer) } => { + if let Ok(mut guard) = writer_2.try_lock() { + if let Some(writer) = guard.as_mut() { + for sample in buffer.iter() { + let sample = cpal::Sample::to_i16(sample); + writer.write_sample(sample).ok(); + } + } + } + }, + cpal::StreamData::Input { buffer: cpal::UnknownTypeInputBuffer::I16(buffer) } => { + if let Ok(mut guard) = writer_2.try_lock() { + if let Some(writer) = guard.as_mut() { + for &sample in buffer.iter() { + writer.write_sample(sample).ok(); + } + } + } + }, + cpal::StreamData::Input { buffer: cpal::UnknownTypeInputBuffer::F32(buffer) } => { + if let Ok(mut guard) = writer_2.try_lock() { + if let Some(writer) = guard.as_mut() { + for &sample in buffer.iter() { + writer.write_sample(sample).ok(); + } + } + } + }, + _ => (), + } + }); + }); + + // Let recording go for roughly three seconds. + std::thread::sleep(std::time::Duration::from_secs(10)); + recording.store(false, std::sync::atomic::Ordering::Relaxed); + writer.lock().unwrap().take().unwrap().finalize()?; + println!("Recording {} complete!", PATH); + Ok(()) +} + +fn sample_format(format: cpal::SampleFormat) -> hound::SampleFormat { + match format { + cpal::SampleFormat::U16 => hound::SampleFormat::Int, + cpal::SampleFormat::I16 => hound::SampleFormat::Int, + cpal::SampleFormat::F32 => hound::SampleFormat::Float, + } +} + +fn wav_spec_from_format(format: &cpal::Format) -> hound::WavSpec { + hound::WavSpec { + channels: format.channels as _, + sample_rate: format.sample_rate.0 as _, + bits_per_sample: (format.data_type.sample_size() * 8) as _, + sample_format: sample_format(format.data_type), + } +} diff --git a/src/main.rs b/src/main.rs index a66b3c7b07..4cafd72738 100644 --- a/src/main.rs +++ b/src/main.rs @@ -9,6 +9,8 @@ extern crate wavy; use std::f64; use wavy::*; +use sample::Signal; +use sample::signal; //use signal; use std::collections::VecDeque; @@ -48,6 +50,7 @@ fn record2() -> Result<(), AudioError> { //let mut last_rsample = None; let mut i = 0; + let mut sine_signal = signal::rate(44_100.0).const_hz(400.0).sine(); speaker.play(&mut || { @@ -56,6 +59,13 @@ fn record2() -> Result<(), AudioError> { //println!("Sin: {}", y); let l = (y * 500.0) as i16; + let mut frame = sine_signal.take(1); + let f = frame.next().unwrap(); + + println!("Frame: {:?}", f); + //let x = frame.next().unwrap(); + //let l = (x * 500.0) as i16; + AudioSample::stereo(l, l) /*if let Some((lsample, rsample)) = buffer.pop_front() {