admin管理员组

文章数量:1406152

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 bee 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?

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 bee 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?

Share Improve this question edited Feb 26, 2017 at 13:24 Peter Quiring asked Feb 26, 2017 at 3:56 Peter QuiringPeter Quiring 1,7161 gold badge17 silver badges22 bronze badges 2
  • You can do it synchronously with a bit of a hack, like I describe here. This still won't be guaranteed to be before some independent async thing. Maybe take a look at this question stackoverflow./questions/15040126/… – Paul S. Commented Feb 26, 2017 at 13:26
  • @Paul - interesting hack. I found the soln posted below, thanks. Just don't use a Blob ;) – Peter Quiring Commented Feb 26, 2017 at 13:46
Add a ment  | 

1 Answer 1

Reset to default 7

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.

本文标签: websocketJavaScript Convert Blob to Float32Array (or other Typed Arrays)Stack Overflow