Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript readAsArrayBuffer returns empty Array Buffer

I am trying to read a local file using the FileReader readAsArrayBuffer property. The read is success and in the "onload" callback, I see the Array Buffer object in reader.result. But the Array Buffer is just empty. The length is set, but not the data. How do I get this data?

Here is my code

<!DOCTYPE html>
<html>

<body>
    <input type="file" id="file" />
</body>

<script>
    function handleFileSelect(evt) {

        var files = evt.target.files; // FileList object

        var selFile = files[0];
        var reader = new FileReader();
        reader.onload = function(e) {
            console.log(e.target.result);
        };

        reader.onerror = function(e) {
            console.log(e);
        };
        reader.readAsArrayBuffer(selFile);
    }


    document.getElementById('file').addEventListener('change', handleFileSelect, false);
</script>

</html>

the console output for reader.result

e.target.result
ArrayBuffer {}
e.target.result.byteLength
25312

Can anyone tell me how to get this data? is there some security issue? There is no error, the onerror is not executed.

From comments: Can you please let me know how to access the buffer contents? I am actually trying to play an audio file using AudioContext... For that I would need the buffer data...

like image 540
Anand N Avatar asked Jun 05 '14 10:06

Anand N


2 Answers

Here is how to read array buffer and convert it into binary string,

function onfilechange(evt) {
var reader = new FileReader(); 
reader.onload = function(evt) {
  var chars  = new Uint8Array(evt.target.result);
  var CHUNK_SIZE = 0x8000; 
  var index = 0;
  var length = chars.length;
  var result = '';
  var slice;
  while (index < length) {
    slice = chars.subarray(index, Math.min(index + CHUNK_SIZE, length)); 
    result += String.fromCharCode.apply(null, slice);
    index += CHUNK_SIZE;
  }
  // Here you have file content as Binary String in result var
};
reader.readAsArrayBuffer(evt.target.files[0]);
}

If you try to print ArrayBuffer via console.log you always get empty object {}

like image 73
Rohit Singh Sengar Avatar answered Nov 15 '22 18:11

Rohit Singh Sengar


Well, playing a sound using the AudioContext stuff isn't actually that hard.

  1. Set up the context.
  2. Load any data into the buffer (e.g. FileReader for local files, XHR for remote stuff).
  3. Setup a new source, and start it.

All in all, something like this:

var context = new(window.AudioContext || window.webkitAudioContext)();

function playsound(raw) {
    console.log("now playing a sound, that starts with", new Uint8Array(raw.slice(0, 10)));
    context.decodeAudioData(raw, function (buffer) {
        if (!buffer) {
            console.error("failed to decode:", "buffer null");
            return;
        }
        var source = context.createBufferSource();
        source.buffer = buffer;
        source.connect(context.destination);
        source.start(0);
        console.log("started...");
    }, function (error) {
        console.error("failed to decode:", error);
    });
}

function onfilechange(then, evt) {
    var reader = new FileReader();
    reader.onload = function (e) {
        console.log(e);
        then(e.target.result);
    };
    reader.onerror = function (e) {
        console.error(e);
    };
    reader.readAsArrayBuffer(evt.target.files[0]);
}


document.getElementById('file')
  .addEventListener('change', onfilechange.bind(null, playsound), false);

See this live in a jsfiddle, which works for me in Firefox and Chrome.

I threw in a console.log(new Uint8Array()) for good measure, as browser will usually log the contents directly (if the buffer isn't huge). For other stuff that you can do with ArrayBuffers, see e.g. the corresponding MDN documentation.

like image 43
nmaier Avatar answered Nov 15 '22 19:11

nmaier