将波流与NAudio混合

时间:2014-02-15 13:43:41

标签: c# naudio wave

过去几天我一直在使用NAudio混合这种格式的两个波形文件:

SampleRate:8000 BitsPerSample:8 频道:1 阻止对齐频道:1 每秒位数:8000

正如我从https://naudio.codeplex.com/discussions/251475发现的那样,首先我应该将它们转换为32位ieeefloatingpoint编码,然后将转换后的流添加到WaveMixerStream32。之后,我应该使用Wave32To16Stream将混合数据转换为16位/样本流,将获得的流转换为单声道,最后将单声道16位/样本转换为单声道8位/样本。

我根据我的解释编写了这些代码行:

    WaveFileReader r1 = new WaveFileReader(...);
    WaveFileReader r2 = new WaveFileReader(...);

    WaveFormat OutputWaveFormat = WaveFormat.CreateCustomFormat(WaveFormatEncoding.Pcm, 8000, 1, 16000, 2, 16);
    WaveFormat InputWaveFormat = WaveFormat.CreateALawFormat(8000, 1);

    WaveFormatConversionStream ConversionStream1 = new WaveFormatConversionStream(OutputWaveFormat, r1);
    WaveFormatConversionStream ConversionStream2 = new WaveFormatConversionStream(OutputWaveFormat, r2);

    WaveChannel32 WaveChannel32_1 = new WaveChannel32(ConversionStream1);
    WaveChannel32 WaveChannel32_2 = new WaveChannel32(ConversionStream2);

    WaveMixerStream32 mixer32 = new WaveMixerStream32();
    mixer32.AddInputStream(WaveChannel32_1);

    mixer32.AddInputStream(WaveChannel32_2);//(*)

    Wave32To16Stream stereo16 = new Wave32To16Stream(mixer32);
    StereoToMonoProvider16 mono16 = new StereoToMonoProvider16(m_Wave32To16Stream);

在行(*)之后我有一个这样的流:0 0 32 60 0 0 32 60 0 0 59 126 0 0 59 126 ... 但在应用Wave32To16Stream之后,我在stereo16中有一系列零,所以在mono16中! 我该怎么办呢?

1 个答案:

答案 0 :(得分:0)

答案非常简单。我只需要将ALaw转换为PCM然后 添加两个波流,我是使用G711代码项目文章中的ALawDecoder完成的。

r1 = new WaveFileReader(...);
r2 = new WaveFileReader(...);
r1.Read(arr1, 0, arr1.Length);    
r2.Read(arr2, 0, arr2.Length);
short[] firstPCM16 = ALawDecoder.ALawDecode(arr1);
short[] secondPCM16 = ALawDecoder.ALawDecode(arr2);
byte[] result1 = new byte[firstPCM16.Length * sizeof(short)];
byte[] result1 = new byte[secondPCM16.Length * sizeof(short)];
Buffer.BlockCopy(firstPCM16, 0, result1, 0, result1.Length);
Buffer.BlockCopy(secondPCM16, 0, result2, 0, result2.Length);
for (...)
{                        
    mixed[i] = (byte)(result1[i] + result2[i]);//No need to dividing by 2 because r1  and r2 are 8 bit ALaw and return value of ALawDecoder is 16 bit pcm
}