无法在分离的ArrayBuffer上执行ArrayBuffer.prototype.slice

时间:2016-12-11 02:35:21

标签: javascript web-worker arraybuffer

我正在尝试使用BlobArrayBuffer创建.slice(),因为我需要复制ArrayBuffer,因为我知道它将来会被更改(byteLength 1}}将是0)我无法控制/想要改变的代码。

new Blob([data2.payload.slice()], {type: "video/MP2T"})

我收到错误

Cannot perform ArrayBuffer.prototype.slice on a detached ArrayBuffer

Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36

在Windows 7 x64上。

还有其他方法可以复制ArrayBuffer吗? This way not does actual copyother ways does not seems to be pretty straightforward

ArrayBuffer.transfer()看起来不错,但他们的polyfill会产生错误

Source and destination must be ArrayBuffer instances

2 个答案:

答案 0 :(得分:1)

这是我的错,我一直对不清楚的错误消息感到困惑,在这种情况下无法做任何事情,因为Blob创建data2.payload已经有byteLength: 0

通常情况下

var from = new ArrayBuffer(0);
var to = from.slice();
var to = from.slice(0);

toArrayBufferbyteLength: 0,在这种情况下它是触发错误,因为在data2.payload传递给我的代码之前,它在web worker中被修改,以便避免在主线程和Web工作者之间复制片段,data2.payload所有权转移给工作者。

答案 1 :(得分:0)

尝试使用new Blob([new Uint8Array(data2.payload.slice(0))], {type: "video/MP2T"})

this fiddle

中查看
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://fiddle.jshell.net/img/logo.png", true);
xhr.responseType = "arraybuffer";
xhr.onload = function(e) {
  var binaryArray = new Uint8Array(this.response.slice(0)); // use UInt8Array for binary
  var blob = new Blob([binaryArray], { type: "image/png" });
  var URL = window.URL || window.webkitURL;
  var imageUrl = URL.createObjectURL(blob); // create url
  document.getElementById("image").src = imageUrl;
};
xhr.send();