获取WAV文件的PCM值

时间:2013-07-01 12:51:28

标签: c# audio fft pcm

我有一个.wav单声道文件(16位,44.1kHz),我正在使用下面的代码。如果我没有错,这将给出一个介于-1和1之间的值的输出,我可以应用FFT(稍后将转换为频谱图)。但是,我的输出不在-1和1附近。

这是我输出的一部分

7.01214599609375  
17750.2552337646  
8308.42733764648  
0.000274658203125  
1.00001525878906  
0.67291259765625  
1.3458251953125  
16.0000305175781  
24932  
758.380676269531  
0.0001068115234375    

这是我从其他帖子中获得的代码
修改1:

 public static Double[] prepare(String wavePath, out int SampleRate)
    {
        Double[] data;
        byte[] wave;
        byte[] sR = new byte[4];
        System.IO.FileStream WaveFile = System.IO.File.OpenRead(wavePath);
        wave = new byte[WaveFile.Length];
        data = new Double[(wave.Length - 44) / 4];//shifting the headers out of the PCM data;
        WaveFile.Read(wave, 0, Convert.ToInt32(WaveFile.Length));//read the wave file into the wave variable
        /***********Converting and PCM accounting***************/
       for (int i = 0; i < data.Length; i += 2)
        {
             data[i] = BitConverter.ToInt16(wave, i) / 32768.0;
        }


        /**************assigning sample rate**********************/
        for (int i = 24; i < 28; i++)
        {
            sR[i - 24] = wave[i];
        }
        SampleRate = BitConverter.ToInt16(sR, 0);
        return data;
    }  

编辑2:我每次获得第2个数字时输出0

0.009002685546875
0
0.009613037109375
0
0.0101318359375
0
0.01080322265625
0
0.01190185546875
0
0.01312255859375
0
0.014068603515625

1 个答案:

答案 0 :(得分:3)

如果您的样本是16位(似乎是这种情况),那么您希望使用Int16。样本数据的每2个字节是带符号的16位整数,范围为-32768 .. 32767,包括在内。

如果要将带符号的Int16转换为从-1到1的浮点值,则必须除以Int16.MaxValue + 1(等于32768)。所以,你的代码变成了:

for (int i = 0; i < data.Length; i += 2)
{
    data[i] = BitConverter.ToInt16(wave, i) / 32768.0;
}

我们在这里使用32768,因为值已签名。

所以-32768/32768将给出-1.0,而32767/32768给出0.999969482421875。

如果使用65536.0,那么您的值将仅在-0.5 .. 0.5。

范围内
相关问题