C ++ 16位读取文件的Wav [英] C++ reading 16bit Wav file
问题描述
我无法读一个16位的.wav文件。我在标题信息读出,但转换似乎不工作。
I'm having trouble reading in a 16bit .wav file. I have read in the header information, however, the conversion does not seem to work.
例如,在Matlab如果我读波形文件我得到以下类型的数据:
For example, in Matlab if I read in wave file I get the following type of data:
-0.0064, -0.0047, -0.0051, -0.0036, -0.0046, -0.0059, -0.0051
不过,在我的C ++程序将返回以下内容:
However, in my C++ program the following is returned:
0.960938, -0.00390625, -0.949219, -0.00390625, -0.996094, -0.00390625
我需要的数据重新presented以同样的方式。现在, 8位
.wav文件,我做了以下内容:
I need the data to be represented the same way. Now, for 8 bit
.wav files I did the following:
uint8_t c;
for(unsigned i=0; (i < size); i++)
{
c = (unsigned)(unsigned char)(data[i]);
double t = (c-128)/128.0;
rawSignal.push_back(t);
}
这个工作,但是,当我这样做是为了16位:
This worked, however, when I did this for 16bit:
uint16_t c;
for(unsigned i=0; (i < size); i++)
{
c = (signed)(signed char)(data[i]);
double t = (c-256)/256.0;
rawSignal.push_back(t);
}
不工作,显示输出(上图)。
Does not work and shows the output (above).
我采用的标准发现这里
其中,数据
是字符
阵列和 rawSignal
是一个的std ::矢量&lt;&双GT;
我可能只是递过转换错了,但似乎无法找出。任何人有什么建议吗?
Where data
is a char
array and rawSignal
is a std::vector<double>
I'm probably just handing the conversion wrong but cannot seem to find out where. Anyone have any suggestions?
感谢
编辑:
这是什么现在显示(在图中):
This is what is now displaying (In a graph):
这就是它应该显示:
推荐答案
在这里有几个问题:
- 8位wav文件是无符号,但16位的wav文件进行签名。因此,在由卡尔和Jay答案给出的减法步骤是不必要的。 I $他们只是从code复制p $ psume,但他们错了。
- 16位波有一个范围从-32,768至32,767,而不是从-256到255,让您在使用反正不正确的乘法。
- 16位wav文件是2个字节,所以你必须阅读的两个字节做一个样品,没有之一。你出现一次要读取一个字符。当你读的字节数,可能需要交换它们,如果你的本地字节顺序是不小端。
假设小尾数的架构,你的code看起来会像这样(非常靠近卡尔的答案):
Assuming a little-endian architecture, your code would look more like this (very close to Carl's answer):
for (int i = 0; i < size; i += 2)
{
int c = (data[i + 1] << 8) | data[i];
double t = c/32768.0;
rawSignal.push_back(t);
}
为大端架构:
for (int i = 0; i < size; i += 2)
{
int c = (data[i] << 8) | data[i+1];
double t = c/32768.0;
rawSignal.push_back(t);
}
这code是未经检验的,所以请LMK,如果它不能正常工作。
That code is untested, so please LMK if it doesn't work.
这篇关于C ++ 16位读取文件的Wav的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!