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 clien...

问题:

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?


回答1:

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.

  • 发表于 2019-03-29 12:58
  • 阅读 ( 271 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除