简体   繁体   中英

JavaScript XMLHttpRequest.responseType as "arraybuffer" -- how to get current arraybuffer chunk

I'm trying to stream a from the client side to a server side, to later stream the video back to another client.

The point is:

How can I get chunks of a video from client-side JavaScript (that can be sent to a server)?

using this code, for example:

var x = new XMLHttpRequest();
        var url = location.href;
        x.onreadystatechange = function(){
            if(x.readyState == 200) {
                console.log("done");
            } else {
                console.log("chunk",x.response); //this is null until readyState is 200 anyway
            }

        }
        x.onprogress = e => {
            console.log("EE",e.target.response); //also null if resposneType is arraybuffer
        };
        x.responseType="arraybuffer";
        x.open("GET","http://localhost:88/videoplayback.mp4",true);
        x.send("");

When I try to print the response before its finished loading (to get it by chunks) then its simply null; the arraybuffer only returns as the respnse when its finished loading.

If I take out the responsetype and just leave it as plain text, then indeed some unicode-characters get printed to the screen for each readystatechange even before its finished, only an arraybuffer doesn't.

So: is this the best way to stream a video from the client to server, and if so, how can I actually do it? and if not, what's a better way?

Indeed, arraybuffer or blob responseTypes do not allow access of chunk of data until the download is complete.

Now, there are ways... For instance in newest browsers, you could start a ReadableStream from the fetch API , or from Firefox you could set the responseType to "moz-chunked-buffer" , but that's not what you need at all here.

What you are describing is exactly what WebRTC has been made for. So the best way is to run a STUN/TURN server, and to stream your media through it using the MediaStream API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM