[英]Incorrect audio data when saving wav file using C++ (based on a C# program)
我编写了一个C#函数来保存音频数据,该函数可以正常工作。 这是用于将数据写入流的原始函数:
public override void store(double data)
// stores a sample in the stream
{
double sample_l;
short sl;
sample_l = data * 32767.0f;
sl = (short)sample_l;
stream.WriteByte((byte)(sl & 0xff));
stream.WriteByte((byte)(sl >> 8));
stream.WriteByte((byte)(sl & 0xff));
stream.WriteByte((byte)(sl >> 8));
}
我将其转换为一些C ++代码,并用于将数据输出到wav文件:
double data;
short smp;
char b1, b2;
int i;
std::ofstream sfile(fname);
...
for (i = 0; i < tot_smps; i++)
{
smp = (short)(rend() * 32767.0);
b1 = smp & 0xff;
b2 = smp >> 8;
sfile.write((char*)&b1, sizeof(char));
sfile.write((char*)&b2, sizeof(char));
sfile.write((char*)&b1, sizeof(char));
sfile.write((char*)&b2, sizeof(char));
}
rend总是在-1和1之间。当我听/看C ++程序中的wav文件时,会有额外的嗡嗡声。 与原始C#代码相比,C ++代码中的数据转换似乎有所不同,导致两个不同程序输出的数据/声音不同。
默认情况下,当您使用C ++打开流时,它以文本模式打开,可以执行将某些字符序列转换为其他字符序列的操作(最著名的是0x0a
可以变成0x0d 0x0a
(从'\\n'
到"\\r\\n"
))。
您需要以二进制模式打开流:
std::ofstream sfile(fname, std::ios::out | std::ios::binary);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.