There are many Q&A's about converting blobs or Uint8Array
to base64. But I have been unable to find how to convert from 32-bit arrays to base64. Here is an attempt.
function p(msg) { console.log(msg) }
let wav1 = [0.1,0.2,0.3]
let wav = new Float32Array(wav1)
p(`Len array to encrypt=${wav.length}`)
let omsg = JSON.stringify({onset: { id: 'abc', cntr: 1234}, wav: atob(wav) })
p(omsg)
The atob
gives:
Uncaught InvalidCharacterError: Failed to execute 'atob' on 'Window':
The string to be decoded is not correctly encoded."
What intermediate step is needed to allow proper encoding of the floats to base64 ? Note that I have also tried TweetNacl-util
instead of atob
this way:
nacl.util.encodeBase64(wav)
This results in the same error.
Update Using JSON.stringify
directly converts each float element into its ascii equivalent - which bloats the datasize . For the above that is:
"0.10000000149011612,"1":0.20000000298023224,"2":0.30000001192092896
We are transferring large arrays so this is a suboptimal solution.
Update The crucial element of the solution in the accepted answer is using Float32Array(floats).buffer
. I was unaware of the buffer
attribute.