RustAudio / cpal

Cross-platform audio I/O library in pure Rust
Apache License 2.0
2.59k stars 344 forks source link

Audio sampling data problem #882

Open hcl-z opened 3 months ago

hcl-z commented 3 months ago
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 🥲

dheijl commented 3 months ago

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)?

hcl-z commented 3 months ago

@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