Skip to content

Audio sampling data problem #882

Open
@hcl-z

Description

@hcl-z
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 🥲

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions