Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Audio sampling data problem #882

Open
hcl-z opened this issue May 10, 2024 · 2 comments
Open

Audio sampling data problem #882

hcl-z opened this issue May 10, 2024 · 2 comments

Comments

@hcl-z
Copy link

hcl-z commented May 10, 2024

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
Copy link
Contributor

dheijl commented May 10, 2024

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
Copy link
Author

hcl-z commented May 10, 2024

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants