0

I am recording my webcam with MediaRecoder and sending each blob back to sever using Websocket as such :

 recorder = new MediaRecorder(canvasStream);
            recorder.ondataavailable = e => {
                ws.send(e.data)
            }

which works fine, however I want to have more control over the type of message or data that will be send through Websocket and therefore I went with the classic

ws.send(JSON.stringify({ type: 'REC', data: e.data }))

to no avail. I cannot obviously Parse the data back on the server. How can I send a blob to the server while stringifying my message?

4
  • 1
    "To no avail" meaning what? It should work. If it didn't, please give us an example of something you had trouble with. Commented Sep 22, 2022 at 20:29
  • 1
    ...strigify ? Surely there's an error on the browser console for this. Commented Sep 22, 2022 at 20:31
  • I think it's a typo here on stack only, and it will be already obvious if its in his IDE, so I would see what the ws.send function does to e.data it could call the toString so try it, ws.send(JSON.stringify({ type: 'REC', data: e.data.toString() })) Commented Sep 22, 2022 at 20:32
  • There was a typo, I edited it. Commented Sep 22, 2022 at 20:41

1 Answer 1

3

Json is a text-based format, it cannot directly include binary data like Blobs. What you can do is to obtain the Blob's arrayBuffer, encode it with base64 or hex and send it as text. This will make the upload 1.5-2 times larger though.

Alternatively, you can try a binary transport, like MessagePack instead of json.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried messagepack and ran into the same thing with import { unpack, pack } from 'msgpackr'; let serializedAsBuffer = pack(value); let data = unpack(serializedAsBuffer); Is there like a trick involved into sending blobs?
@Hypothesis: you have to obtain raw binary data from a blob (blob.arrayBuffer) and then give that data to msgpack.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.