cpal icon indicating copy to clipboard operation
cpal copied to clipboard

Audio sampling data problem

Open hcl-z opened this issue 1 year ago • 2 comments

use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{Stream, StreamConfig};

fn main() -> Result<(), anyhow::Error> {
    let host = cpal::default_host();
    let device = host.default_input_device().expect("no device");
    let config: StreamConfig = device.default_input_config()?.into();

    // 创建录音流
    let input_stream = device.build_input_stream(
        &config,
        move |data: &[f32], _: &cpal::InputCallbackInfo| {

            let rms = calculate_rms(data);

            println!("db:", 20.0 * rms.log10());
        },
        |err| {
            eprintln!("error: {}", err);
        },
        Option::None,
    )?;

    input_stream.play()?;

    std::thread::sleep(std::time::Duration::from_secs(10));

    Ok(())
}

fn calculate_rms(data: &[f32]) -> f32 {
    let mut sum = 0.0;
    for &sample in data {
        sum += sample * sample;
    }
    (sum / data.len() as f32).sqrt()
}

I wanted to get the DB value of the recording, but why is it that the data sampled is very close to 0, and the DB value calculated is basically kept at -50。Can someone help 🥲

hcl-z avatar May 10 '24 14:05 hcl-z

Are you sure that you're capturing the correct input device? In Windows you can check this in the Windows Soundmixer and compare it with your selected device name. Is this a device with 1 channel (mono) or 2 (stereo)?

dheijl avatar May 10 '24 14:05 dheijl

@dheijl I just took the default input device and the default input configuration. The device and configuration information is as follows:

device:Ok("MacBook Pro microPhone");
config:StreamConfig { channels: 1, sample_rate: SampleRate(96000), buffer_size: Default }

In fact, the final DB value did vary depending on the volume of the recording, but it didn't match my expectations, and I had no idea

hcl-z avatar May 10 '24 15:05 hcl-z