Skip to content

Instantly share code, notes, and snippets.

@debamitro
Created Dec 6, 2021
Embed
What would you like to do?
some test code using Rust's cpal library which reads audio data from the microphone
fn catch_error(err: StreamError) {
println!("found error {:?}",err);
}
fn get_audio() {
let mut num_samples = Arc::new(AtomicUsize::new(0));
let num_samples2 = num_samples.clone();
let catch_data = move |data: &[f32], _info: &InputCallbackInfo| {
num_samples.fetch_add(data.len(), Ordering::Relaxed);
};
let host = cpal::default_host();
if let Some(device) = host.default_input_device() {
if let Ok(config) = device.default_input_config() {
let custom_config = cpal::StreamConfig {
channels : 2,
sample_rate: cpal::SampleRate(44100),
buffer_size: cpal::BufferSize::Default
};
if let Ok(stream) = device.build_input_stream (&custom_config,
catch_data,
catch_error) {
stream.play();
std::thread::sleep(std::time::Duration::from_secs(20));
stream.pause();
println!("number of samples {:?}",num_samples2);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment