3

I have an object with an audio blob inside of it. When I call JSON.stringify on the object, the blob disappears. How to stringify a binary blob in an object ?

The audio blob is from the sox-element and in this case is of mime type 'audio/wav'.

let blob = this/soxElem.getBlob();
let object = {
  audio: blob,
  name: "hi"
}

console.log(JSON.stringify(object))

The console shows {audio:{}, name: "hi"}. The blob is gone.

Matt
  • 509
  • 2
  • 14

1 Answers1

2

One way to do it is to convert to an array which JSON can handle :

let ab = await this.soxElem.getBlob().arrayBuffer();
let object = {
  audio: Array.from(new Uint8Array(ab)),
  name: "hi"
}

On the receiving side (e.g. with Node.js) decode it like so :

let binaryData = Buffer.from(data.audio);
Matt
  • 509
  • 2
  • 14
  • If it's to send that data to a server they'd be better sending it as multipart from the beginning. This encoding to JSON will be even bigger than a base64 encoding which is already ~37% bigger than the binary data it represents. – Kaiido May 20 '21 at 07:32
  • What do you think is a btter way ? – Matt May 21 '21 at 03:38