Unity麦克风采样audio44100HZ 转16000HZ

1、手机在麦克风有部分手机识别16000HZ音频时会导致失真。unity默认是44100HZ

但是发到阿里的语音sdk 只识别8K和16K的所以需要转换采样一下

        AudioClip ResampleAudio44100(AudioClip sourceClip)
        {
            // 1. 提取原始数据
            float[] sourceData = new float[sourceClip.samples * sourceClip.channels];
            sourceClip.GetData(sourceData, 0);

            // 2. 抗混叠滤波(截止频率8kHz)
            float[] filtered = ApplyFIRFilter(sourceData, 8000, 44100);

            // 3. 非整数倍重采样(44100→16000)
            float ratio = 16000f / 44100f;
            float[] resampledData  = new float[Mathf.FloorToInt(filtered.Length * ratio)];
            for (int i = 0; i < resampledData.Length; i++)
            {
                float srcIndex = i / ratio;
                int floor = Mathf.FloorToInt(srcIndex);
                float t = srcIndex - floor;
                // 线性插值
                resampledData[i] = Mathf.Lerp(filtered[floor], filtered[Mathf.Min(floor + 1, filtered.Length - 1)], t);
            }

            // 4. 创建新AudioClip
            AudioClip newClip = AudioClip.Create("Resampled", resampledData.Length, 1, 16000, false);
            newClip.SetData(resampledData, 0);
            return newClip;
        }

 float[] coeffs = { 0.001f, 0.02f, 0.05f, 0.12f, 0.2f, 0.12f, 0.05f, 0.02f, 0.001f }; // 示例系数
 // FIR低通滤波器实现
 private float[] ApplyFIRFilter(float[] input, float cutoffFreq, int sourceRate)
 {
     float[] output = new float[input.Length];
     int kernelRadius = coeffs.Length / 2;

     for (int i = kernelRadius; i < input.Length - kernelRadius; i++)
     {
         float sum = 0;
         for (int j = 0; j < coeffs.Length; j++)
         {
             sum += input[i - kernelRadius + j] * coeffs[j];
         }
         output[i] = sum;
     }
     return output;
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虾米神探

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值