Naudio - Convert 32 bit wav to 16 bit wav

半城伤御伤魂 提交于 2019-12-05 02:11:33

问题


I've been trying to convert a 32 bit stereo wav to 16 bit mono wav. I use naudio to capture the sound I and thought that using just the two of four more significant bytes will work.

Here is the DataAvailable implementation:

void _waveIn_DataAvailable(object sender, WaveInEventArgs e)
{
     byte[] newArray = new byte[e.BytesRecorded / 2];
     short two;
     for (int i = 0, j = 0; i < e.BytesRecorded; i = i + 4, j = j + 2)
     {
          two = (short)BitConverter.ToInt16(e.Buffer, i + 2);


          newArray[j] = (byte)(two & 0xFF);
          newArray[j + 1] = (byte)((two >> 8) & 0xFF);
     }
     //do something with the new array:
}

Any help would be greatly appreciated!


回答1:


I finally found the solution. I just had to multiply the converted value by 32767 and cast it to short:

void _waveIn_DataAvailable(object sender, WaveInEventArgs e)
{
    byte[] newArray16Bit = new byte[e.BytesRecorded / 2];
    short two;
    float value;
    for (int i = 0, j = 0; i < e.BytesRecorded; i += 4, j += 2)
    {
        value = (BitConverter.ToSingle(e.Buffer, i));
        two = (short)(value * short.MaxValue);

        newArray16Bit[j] = (byte)(two & 0xFF);
        newArray16Bit[j + 1] = (byte)((two >> 8) & 0xFF);
    }
}



回答2:


A 32-bit sample can be as high as 4,294,967,295 and a 16-bit sample can be as high as 65,536. So you'll have to scale down the 32-bit sample to fit into the 16-bit sample's range. More or less, you're doing something like this...

SixteenBitSample = ( ThirtyTwoBitSample / 4294967295 ) * 65536;

EDIT:

For the stereo to mono portion, if the two channels have the same data, just dump one of them, otherwise, add the wave forms together, and if they fall outside of the sample range (65,536) then you'll have to scale them down similarly to the above equation.

Hope that helps.



来源:https://stackoverflow.com/questions/13995259/naudio-convert-32-bit-wav-to-16-bit-wav

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!