将32位wav阵列转换为x位

时间:2017-02-25 18:18:35

标签: c# converter wav bitrate

我有一个32位的wav数组,我想把它转换为8位

所以我尝试将此功能转换为32到16

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);
    }
}

并修改它以x位为目的地

    private byte[] Convert32BitRateToNewBitRate(byte[] bytes, int newBitRate)
    {
        var sourceBitRate = 32;

        byte[] newArray = new byte[bytes.Length / (sourceBitRate / newBitRate)];

        for (int i = 0, j = 0; i < bytes.Length; i += (sourceBitRate / 8), j += (newBitRate / 8))
        {
            var value = (BitConverter.ToSingle(bytes, i));
            var two = (short)(value * short.MaxValue);

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

        return newArray;
    }

我的问题是,我不确定如何转换&#34; for&#34;中的代码。循环,我试图调试它,但我无法弄清楚它是如何工作的。

我在这里看到:simple wav 16-bit / 8-bit converter source code?,他们将值除以256得到16到8,我试图除以256得到32到16但它没有工作

        for (int i = 0, j = 0; i < bytes.Length; i += sourceBitRateBytes, j += newBitRateBytes)
        {
            var value = BitConverter.ToInt32(bytes, i);
            value /= (int)Math.Pow(256, sourceBitRate / newBitRate / 2.0);

            var valueBytes = BitConverter.GetBytes(value);

            for (int k = 0; k < newBitRateBytes; k++)
            {
                newArray[k + j] = valueBytes[k];
            }

1 个答案:

答案 0 :(得分:0)

for循环在以下位置仍然使用16位:

  • short.MaxValue。请改用byte.MaxValue
  • [j][j+1]分配两个字节。仅分配一个字节。

我没有剩下的程序,没有样本数据,所以我很难尝试。但我会说下面关于正确的声音

for (int i = 0, j = 0; i < bytes.Length; i += (sourceBitRate / 8), j += (newBitRate / 8))
{
    var value = (BitConverter.ToSingle(bytes, i));
    var two = (byte)(value * byte.MaxValue);

    newArray[j] = two;
}

请注意,这仅适用于8位,因此newBitRate必须为8,否则无效。它应该不是该方法的参数。