在Javascript中将ArrayBuffer类型的结果存储在一个数组中

时间:2022-10-07 21:27:38

I am using the HTML5 FileReader and File API to make a offline music player. This also includes a basic playlist feature.

我正在使用HTML5 FileReader和File API来制作离线音乐播放器。这还包括基本播放列表功能。

Now, when the user selects multiple files, I am retrieving those files as an ArrayBuffer.

现在,当用户选择多个文件时,我将这些文件检索为ArrayBuffer。

Problem is, I want to store these returned files into a normal array so that they can be used in the playlist later.

问题是,我想将这些返回的文件存储到普通数组中,以便以后可以在播放列表中使用它们。

How can I achieve that in Javascript?

我怎样才能在Javascript中实现这一目标?

function load_files(){
    var files = document.getElementById('file').files;
    var k = files.length;
    for (var i = 0; i < k; i++) {
        var reader = new FileReader();
        reader.onload = function(e) {
            playlist[i] = this.result;
        };
        reader.readAsArrayBuffer(this.files[i]);
        alert(song_counter); 
        initSound(playlist[song_counter]);
    }
}

1 个解决方案

#1


1  

You cannot just store an ArrayBuffer in an array and re-read the file from it. The buffer is used to load a fixed length of bytes and keep them coming so that you don't run out of bytes to play.

您不能只将ArrayBuffer存储在数组中并从中重新读取该文件。缓冲区用于加载固定长度的字节并保持它们的到来,这样就不会耗尽字节数。

Instead you should read all the bytes from the ArrayBuffer into a byteArray and store the byteArrays in an array. You can then replay all the songs from the byte arrays.

相反,您应该将ArrayBuffer中的所有字节读入byteArray并将byteArrays存储在数组中。然后,您可以重放字节数组中的所有歌曲。

If you already have the songs locally (since your question doesn't state where you get the files from) you can just store the path to the file and then reload the file from that.

如果您已经在本地拥有歌曲(因为您的问题没有说明从哪里获取文件),您可以只存储文件的路径,然后从中重新加载文件。

I hope this makes sense.

我希望这是有道理的。

#1


1  

You cannot just store an ArrayBuffer in an array and re-read the file from it. The buffer is used to load a fixed length of bytes and keep them coming so that you don't run out of bytes to play.

您不能只将ArrayBuffer存储在数组中并从中重新读取该文件。缓冲区用于加载固定长度的字节并保持它们的到来,这样就不会耗尽字节数。

Instead you should read all the bytes from the ArrayBuffer into a byteArray and store the byteArrays in an array. You can then replay all the songs from the byte arrays.

相反,您应该将ArrayBuffer中的所有字节读入byteArray并将byteArrays存储在数组中。然后,您可以重放字节数组中的所有歌曲。

If you already have the songs locally (since your question doesn't state where you get the files from) you can just store the path to the file and then reload the file from that.

如果您已经在本地拥有歌曲(因为您的问题没有说明从哪里获取文件),您可以只存储文件的路径,然后从中重新加载文件。

I hope this makes sense.

我希望这是有道理的。