You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用NAudio混合两个byte[]音频块得到单个混合byte[]

使用NAudio混合16位单声道音频块

已知两个音频块均为8000采样率、16位单声道且长度一致,以下是基于NAudio实现的MixChunks方法:

using NAudio.Wave;

public byte[] MixChunks(byte[] rtpChunk, byte[] backChunk)
{
    if (rtpChunk.Length != backChunk.Length)
        throw new ArgumentException("两个音频块长度必须匹配");

    // 用WaveBuffer直接将byte数组映射为short数组(对应16位音频采样)
    var rtpWaveBuffer = new WaveBuffer(rtpChunk);
    var backWaveBuffer = new WaveBuffer(backChunk);
    var mixedWaveBuffer = new WaveBuffer(new byte[rtpChunk.Length]);

    // 遍历每个采样点混合,同时做限幅防止溢出
    for (int i = 0; i < rtpWaveBuffer.ShortBuffer.Length; i++)
    {
        int combined = rtpWaveBuffer.ShortBuffer[i] + backWaveBuffer.ShortBuffer[i];
        // 限制在16位音频的合法范围[-32768, 32767]
        combined = Math.Clamp(combined, short.MinValue, short.MaxValue);
        mixedWaveBuffer.ShortBuffer[i] = (short)combined;
    }

    return mixedWaveBuffer.ByteBuffer;
}

关键说明

  1. WaveBuffer的作用:NAudio的WaveBuffer类可以直接将byte数组转换为对应位深的采样数组(这里是short[]),无需手动处理字节序转换,简化代码。
  2. 限幅处理:两个16位采样相加可能超出short类型的取值范围,必须用Math.Clamp做限幅,否则会出现音频爆音或失真。
  3. 音量调整(可选):如果需要调整两个音频的音量比例,可在相加前给采样乘以系数,比如降低背景音乐音量:
    int combined = rtpWaveBuffer.ShortBuffer[i] + (int)(backWaveBuffer.ShortBuffer[i] * 0.25f);
    

内容的提问来源于stack exchange,提问作者Piercarlo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 21:05:15