我是 NAudio 的新手,我需要实现以下目标:
我有一个 sip 事件,它返回一个 uint rtp 缓冲区,我使用以下代码将其转换为
byte[]
块:
rtpChunk = new byte[buflen];
Marshal.Copy(buf, rtpChunk, 0, buflen);
我还有另外一首
bytes[]
背景音乐。
var backChunk = new byte[buflen];
Array.Copy(bot.BackgroundBuffer, bot.BackgroundBufferIndex, backChunk, 0, buflen);
我需要混合在一起并检索
byte[]
中的混合块,并使用以下代码作为uint rtp数据包发送回来:
Marshal.Copy(mixedChunk, 0, buf, buflen);
那么我怎样才能用NAudio实现:
byte[] mixedChunk = MixChunks(rtpChunk, backChunk);
P.S:购买的块的采样率、比特数、通道是相等的:
8000, 16, 1
谢谢您的帮助, 皮尔卡洛
亲爱的, 感谢您的建议,我搜索并改编了 NAudio github 存储库上找到的一些源代码来实现我的目标,所以我发布了有效的解决方案,可能对其他一些有用。
我假设此代码仅处理原始音频字节,如果您想将结果保存在“.wav”文件中,您需要添加标头。
方法如下:
public static byte[] MixBuffers(int count, params byte[][] bSources)
{
byte[] buffer = new byte[count];
int offset = 0;
byte[] sourceBuffer = new byte[count];
List<Stream> sources = new();
foreach (var chunk in bSources)
sources.Add(new MemoryStream(chunk));
int outputSamples = 0;
sourceBuffer = BufferHelpers.Ensure(sourceBuffer, count);
lock (sources)
{
int index = sources.Count - 1;
while (index >= 0)
{
var source = sources[index];
int samplesRead = source.Read(sourceBuffer, 0, count);
int outIndex = offset;
for (int n = 0; n < samplesRead; n++)
if (n >= outputSamples)
buffer[outIndex++] = sourceBuffer[n];
else
buffer[outIndex++] += sourceBuffer[n];
outputSamples = Math.Max(samplesRead, outputSamples);
index--;
}
}
foreach (var source in sources)
source.Dispose();
return buffer;
}