2

How do you convert a blob that was received with a WebSocket Binary message to a Float32Array (or other Typed Arrays : Uint32, Uint16, etc).

I've tried to use the FileReader but the 'result' takes WAY too long to become available. The result MUST be available on the next received WebSocket message.

If I could get the WebSocket to receive an ArrayBuffer instead of a Blob, that would work. How can I do that?

Peter Quiring
  • 1,648
  • 1
  • 16
  • 21
  • You can do it synchronously with a bit of a hack, like I describe [**here**](http://stackoverflow.com/a/27208593/1615483). This still won't be guaranteed to be before some independent async thing. Maybe take a look at this question http://stackoverflow.com/questions/15040126/receiving-websocket-arraybuffer-data-in-the-browser-receiving-string-instead – Paul S. Feb 26 '17 at 13:26
  • @Paul - interesting hack. I found the soln posted below, thanks. Just don't use a Blob ;) – Peter Quiring Feb 26 '17 at 13:46

1 Answers1

6

Found the solution, is was easy. The WebSocket binaryType default is 'Blob', change it to ArrayBuffer and then convert data to other TypedArrays is fast.

var ws = new WebSocket(...);
ws.binaryType = 'arraybuffer';
ws.onmessage = wsevent;

The message handler might look like this:

var floatArray;
function wsevent(event) {
  if (event.data instanceof ArrayBuffer) {
    floatArray = new Float32Array(event.data);
    return;
  }
  //...handle other ws messages
}

In my code I typically send the binary data in one message and then the next text message would use the binary data.

Peter Quiring
  • 1,648
  • 1
  • 16
  • 21
  • hey, I'm having a similar issue. Could you please elaborate, how to go from ArrayBuffer to Float32Array? I'm new to typed arrays, having some difficulties with it. Thanks! – Andrei Jan 20 '20 at 00:22
  • @Andrei I've expanded the sample code to show how it's done. – Peter Quiring Jan 20 '20 at 17:13