How do I read out the first 4 bytes in javascript,

2020-04-30 03:12发布

问题:

I need to transfer webcam data over the internet from one browser to another.

The webcam is displayed in a HTML5 canvas. Then I get its dataUrl, and turn it into a blob. Then I send this blob to my server.

From what I understand, the blob is essentially a byte array. I've converted it to a byte array on the server-side, it has the same length as blob.size in the browser, so that seems fine. I need to add a sender id to it, so I convert an integer to an array of 4 bytes and add it to the front of the byte array.

Now I need to send this modified blob to the other browser. And this is where I'm confused.

  1. How do I read out the first 4 bytes in javascript and turn it into an integer again?
  2. And how do I cut off the rest of the blob?

回答1:

You can use Blob.slice() method to get bytes.
See docs: https://developer.mozilla.org/en-US/docs/Web/API/Blob.slice

1)

var bytes = blob.slice(0,4);

2)

var arrayOfBytes = [];
for(var i=0;i<blob.size/4;i++){
    arrayOfBytes[i] = blob.slice(i*4,4+(i*4));
}

Note: I didn't test it!