获取WAV文件的PCM值
本文关键字:PCM 文件 WAV 获取 | 更新日期: 2023-09-27 18:20:29
我有一个.wav mono文件(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
如果您的样本是16位(看起来是这样),那么您希望使用Int16
。样本数据的每2个字节是一个范围为-32768的有符号16位整数。。32767,包括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的范围内。