Created
May 20, 2021 14:07
-
-
Save samoylovfp/4ba04f6fa65d7db97a58d5d449b81ca8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate cpal; | |
use std::{process::exit, sync::mpsc::channel}; | |
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; | |
fn main() { | |
//initialise the host | |
let host = cpal::default_host(); | |
//choose available device | |
let device = host.default_input_device().expect("no input device found"); | |
println!("Input device: {:?}", device.name()); | |
let config = device | |
.default_input_config() | |
.expect("Failed to get input config"); | |
println!("Default input config: {:?} ", config); | |
// A flag to indicate that recording is in progress. | |
println!("Listening..."); | |
let (sound_sender, sound_receiver) = channel(); | |
let stream = device | |
.build_input_stream( | |
&config.into(), | |
move |data: &[f32], _: &_| { | |
sound_sender.send(data.to_owned()).unwrap(); | |
}, | |
move |err| {println!("Error reading from source: {}", err)}, | |
) | |
.expect("Failed to create stream"); | |
stream.play().unwrap(); | |
let mut sound_buffer = vec![]; | |
loop { | |
sound_buffer.extend(sound_receiver.recv().unwrap()); | |
// This needs to be replaced with the silence detection and sound processing | |
if sound_buffer.len() >= 44100 { | |
let ints = sound_buffer.iter().map(|f|(*f * 1000.0) as i32); | |
println!("Max is {:?}, min is {:?}", ints.clone().max(), ints.min()); | |
sound_buffer.clear(); | |
} | |
} | |
} | |
/* | |
//return false if the RMS level is higher than silence? (keep recording...) | |
fn write_input_data<T>(input: &[T]) -> bool | |
where | |
T: cpal::Sample, | |
{ | |
let mut rms: usize = 0; | |
let shorts = input.len() / 2; | |
for elem in 0..shorts { | |
let normal = elem; | |
rms += normal * normal; | |
} | |
rms = rms / shorts; //find square root of right side | |
println!("Listening, rms is {}", rms); | |
if rms < 0.1 {}; | |
true | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment