added int to float and float to int helpers

This commit is contained in:
Ahmet Inan 2025-07-30 08:23:44 +02:00
commit 8246c5b5dd

29
wav.hh
View file

@ -35,6 +35,15 @@ class ReadWAV : public ReadPCM<TYPE>
return true; return true;
return false; return false;
} }
static float int2float(int value)
{
union {
int i;
float f;
} u;
u.i = value;
return u.f;
}
public: public:
ReadWAV(const char *name) : is(name, std::ios::binary) ReadWAV(const char *name) : is(name, std::ios::binary)
{ {
@ -123,12 +132,10 @@ public:
stride = channels_; stride = channels_;
for (int n = 0; n < num; ++n) { for (int n = 0; n < num; ++n) {
for (int c = 0; c < channels_; ++c) { for (int c = 0; c < channels_; ++c) {
if (bytes == 4) { if (bytes == 4)
int v = readLE(4); buf[stride * n + c] = int2float(readLE(4));
buf[stride * n + c] = *reinterpret_cast<float *>(&v); else
} else {
buf[stride * n + c] = TYPE(readLE(bytes) - offset) / TYPE(factor); buf[stride * n + c] = TYPE(readLE(bytes) - offset) / TYPE(factor);
}
} }
} }
} }
@ -169,6 +176,15 @@ class WriteWAV : public WritePCM<TYPE>
for (int i = 0; i < b; ++i) for (int i = 0; i < b; ++i)
os.put(255 & (v >> (8 * i))); os.put(255 & (v >> (8 * i)));
} }
static int float2int(float value)
{
union {
float f;
int i;
} u;
u.f = value;
return u.i;
}
public: public:
WriteWAV(const char *name, int rate, int bits, int channels) : WriteWAV(const char *name, int rate, int bits, int channels) :
os(name, std::ios::binary | std::ios::trunc), os(name, std::ios::binary | std::ios::trunc),
@ -242,8 +258,7 @@ public:
for (int n = 0; n < num; ++n) { for (int n = 0; n < num; ++n) {
for (int c = 0; c < channels_; ++c) { for (int c = 0; c < channels_; ++c) {
if (bytes == 4) { if (bytes == 4) {
float v = buf[stride * n + c]; writeLE(float2int(buf[stride * n + c]), 4);
writeLE(*reinterpret_cast<int *>(&v), 4);
} else { } else {
TYPE v = TYPE(offset) + TYPE(factor) * buf[stride * n + c]; TYPE v = TYPE(offset) + TYPE(factor) * buf[stride * n + c];
writeLE(std::nearbyint(std::min(std::max(v, TYPE(min)), TYPE(max))), bytes); writeLE(std::nearbyint(std::min(std::max(v, TYPE(min)), TYPE(max))), bytes);