I have some data generated by the javascript HTML5 web audio api. It generates Float32Array, an array of 32-bit Floating Points, between -1 and 1. I stream the data to my server using a websocket.
I need to convert the 32-bit floating points to 16-bit PCM range between -32768 and +32767 (16-bit signed integer). This then allows the data to be used as a wav file.
I'm having trouble converting. I suspect the answer is to use the struct module, but I can't get the correct formatting.
Best Answer
Here's a sample Python 2.7 program that reads a file containing raw 32-bit floating point audio samples and creates a WAV file containing those samples converted 16-bit signed integer samples:
The code uses
array.array
to convert the 32-bit floating point samples to a Python floats because it should be a bit faster thanstruct.unpack
. It also uses the native machine byte order, just likeFloat32Array
does. It's not possible to usearray.array
to create the 16-bit integer samples because they need to use the little endian byte order regardless of the native machine order. The range conversion is handled by simple Python code.