[英]merge multiple arrayBuffer arrays to single Int16Array
我有這段代碼可以將一些arrayBuffer
添加到數組中。
let buffer = [];
fetch(dataURI)
.then( (res) => res.arrayBuffer() )
.then( (data) => {
buffer.push(data);
});
我需要將結果數組轉換為單個Int16Array
來處理它,我正在嘗試使用此代碼但沒有成功。 我無法獲得我需要的單個 Int16Array
buffer.forEach( (item) => {
samples = [...Int16Array.from(item)];
});
關於我如何繼續的任何建議?
也許用Array.flat()試試這個
let I16 = buffer.map(a => new Int16Array(a)).flat()
您必須將 map 緩沖到 int16 塊,然后將這些塊連接到一個數組中:
const int16Chunks = [];
let byteLength = 0;
fetch(dataURI)
.then(res => res.arrayBuffer())
.then(buffer => {
const chunk = createChunk(buffer, Int16Array.BYTES_PER_ELEMENT);
int16Chunks.push(chunk);
byteLength += chunk.byteLength;
});
稍后,當所有內容都已獲取時:
const bytes = new Uint8Array(byteLength);
let offset = 0;
for (const chunk of int16Chunks) {
bytes.set(offset, chunk);
offset += chunk.length;
}
const result = new Int16Array(bytes.buffer);
最后,創建Chunk createChunk
:
function createChunk(buffer, step) {
const bytes = new Uint8Array(buffer);
const length = Math.ceil(bytes.length / step) * step;
const padded = new Uint8Array(length);
const offset = padded.length - bytes.length;
const chunk = padded.set(offset, bytes);
return chunk;
}
這個問題有點不對勁,因為fetch
請求不會多次將data
推送到緩沖區,但我想這只是您的用例的一個示例,並且您的buffer
會通過不同的提取多次填充。
無論如何,在推送所有內容之后,我將使用以下內容而不是.flat()
:
buffer.push(...data);
// or ...
buffer.push(...new Int16Array(data));
這將立即展平data
,以便一旦完成所有提取,您所要做的就是:
const i16a = Int16Array.from(buffer);
// or ...
const i16a = new Int16Array(buffer);
前面提到的解決方案會在不連接所有接收到的數據的情況下展平數組,因此我認為它不會根據您的要求工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.