使用 C++ 保存 wav 文件时音频数据不正确(基于 C# 程序)
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);
我写了一个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);