Skip to content

Instantly share code, notes, and snippets.

@nmfisher
Last active March 30, 2020 06:08
Show Gist options
  • Save nmfisher/fd056ad152eba8976e9a2f0ea9739b4e to your computer and use it in GitHub Desktop.
Save nmfisher/fd056ad152eba8976e9a2f0ea9739b4e to your computer and use it in GitHub Desktop.
import 'dart:typed_data';
import 'dart:io';
class Half {
static Float32List ToFloat32(ByteData buffer) {
var f32Buffer = ByteData(buffer.lengthInBytes * 2);
for(int i = 0; i < buffer.lengthInBytes; i+=2) {
var half = buffer.getUint16(i, Endian.little);
// get sign by AND 0x800
var sign = half & 0x8000;
// LS sign by 16 bits
sign = sign << 16;
// RS half by 10 to discard mantissa
var exp = half >> 10;
// mask out sign bit by AND 0x1F (0001 1111)
exp = exp & 0x1F;
// convert exp from 5-bit offset-binary to 8-bit offset-binary adding 0111 0000 = 0x70
exp = exp + 0x70;
// LS exp by 23
exp = exp << 23;
// mask out sign/exp by AND 0x03FF (0000 0011 1111 1111)
var mant = half & 0x03FF;
// convert mant from 10-bit offset-binary to 23-bit offset-binary by shifting left 13
mant = mant << 13;
f32Buffer.setInt32(i * 2, sign + exp + mant, Endian.little);
}
return Float32List.view(f32Buffer.buffer);
}
}
void main() async {
var test = await File('test_mono_16b_le.wav').readAsBytes();
print(test.buffer.asByteData().getUint16(0x32, Endian.little)); // 4A00 -> 74
print(Half.ToFloat32(test.buffer.asByteData(0x32, 2)).buffer.asByteData().getFloat32(0));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment