I wrote a C# function to save audio data, which worked without any problems. Here is the original function used to write the data to a stream:
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));
}
I converted this to some C++ code and used it to output data to a wav file:
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 is always between -1 and 1. When I listen to / look at the wav file from the C++ program there is an extra buzzing sound. There seems to be something different about the data conversion in the C++ code compared to the original C# code, resulting in different data / sound being outputted by the two different programs.
By default when you open a stream in C++ it's opened in text mode , which can do things like converting certain character sequences to others (most notably 0x0a
can become 0x0d 0x0a
( '\\n'
to "\\r\\n"
)).
You need to open the stream in binary mode:
std::ofstream sfile(fname, std::ios::out | std::ios::binary);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.