Question

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

Now, when the user selects multiple files, I am retrieving those files as an 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?

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]);
    }
}
Was it helpful?

Solution

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.

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top