0

I would like to send data of different data types via websocket of different data types to a python server. At first, I used to only send a blob that I got from MediaRecorder. That worked perfectly fine.

Now I would like to add a functionality that sends a string to the server and want it to be handled depending on what type is sent.

My idea was to build a json string like so:

myjson={"type": "type_a", "content": "info"}

I tried adding a blob to this dict like shown below.

messageJson = JSON.stringify({"type": "recordedAudio", "content": blob});

When I tried to transform that back to a webm file it didn't. (Media player cannot play file, but no Error message)

async def handler(websocket):
    while True:
         message = await websocket.recv()
         messageAsJSON = json.loads(message)
         messageType = messageAsJSON["type"]
         messageContent = messageAsJSON["content"]
         encode_data = json.dumps(messageContent).encode('utf-8')
         if messageType == "recordedAudio":
             if os.path.isfile("output.wav"):
                 os.remove("output.wav")
             with open("output.wav", 'ab') as f:
                 f.write(encode_data)

Where did I go wrong? From my understanding of blobs something like this should be possible, but I'm not sure. Do I have to convert the blob some how before adding it to the dict?

Emre
  • 144
  • 2
  • 17
  • Does this answer your question? [JSON.stringify or how to serialize binary data as base64 encoded JSON?](https://stackoverflow.com/questions/27232604/json-stringify-or-how-to-serialize-binary-data-as-base64-encoded-json) – relent95 Jan 31 '23 at 02:08
  • @relent95 yes, this was pretty much what I was looking for! Thx! – user16345050 Feb 03 '23 at 12:05

0 Answers0