unity 获取 AudioSource 分贝值

概念界定

以下概念引用自《实验语音学概要》(鲍怀翘,林茂灿):

  1. 声压

  2. 声压级(单位分贝)
    在这里插入图片描述

原理

GetOutputData() 可以获得一段时间内的“瞬时声压”(虽然可能不是非常对但我们就当他是吧),根据声压公式计算声压后,就容易得到分贝值了。

另外本文的参数 refValue 用了0.0001,计算分贝四舍五入相当于计算声压是参考值的多少倍,所以 refValue 不同当然会导致结果不同。

代码

来源:https://answers.unity.com/questions/157940/getoutputdata-and-getspectrumdata-they-represent-t.html

public static class AudioPower
{
    public static float GetDb(this AudioSource audio, int length, float refValue)
    {
        float[] samples = new float[length];
        audio.GetOutputData(samples, 0); // fill array with samples
        var dbLeft = CalulateDb(length, refValue, samples);
        audio.GetOutputData(samples, 1);
        var dbRight = CalulateDb(length, refValue, samples);
        return Mathf.Max(dbLeft, dbRight);
    }

    private static float CalulateDb(int length, float refValue, float[] samples)
    {
        var sum = 0f;
        for (int i = 0; i < length; i++)
        {
            sum += samples[i] * samples[i]; // sum squared samples
        }
        var rmsValue = Mathf.Sqrt(sum / length); // rms = square root of average
        var dbValue = 20 * Mathf.Log10(rmsValue / refValue); // calculate dB
        if (dbValue < -80) dbValue = -80; // clamp it to -160dB min

        return dbValue;
    }
}

其他一些可能有用的链接

  1. CSDN - liu_if_else - 用Unity3D内部频谱分析方法做音乐视觉特效的原理说明https://blog.csdn.net/liu_if_else/article/details/51233799
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值