9

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...

nmaier
  • 29,828
  • 5
  • 59
  • 75
Anand N
  • 352
  • 1
  • 4
  • 11
  • 1
    Why do you think the buffer is empty? Your code does not actually access/inspect the buffer contents at all. Maybe you're confused by the `console.log` output? `console.log()` will not print the contents of the buffer. – nmaier Jun 05 '14 at 10:04
  • Thanks nmaier, I thought the same...but I don't know how to access the buffer contents... 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... Many thanks for your help – Anand N Jun 06 '14 at 06:55
  • 1
    You're using the onload event instead of the onloadend event. Your code will work if you replace the onload event by onloadend. See: https://developer.mozilla.org/en-US/docs/Web/API/FileReader – seb Jun 17 '14 at 07:00
  • @seb it was not the issue. The file that I was using was corrupted... Please check my replies to nmaier below – Anand N Jun 18 '14 at 07:37

2 Answers2

8

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 {}

5

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.

nmaier
  • 29,828
  • 5
  • 59
  • 75
  • I also did the same thing, but was getting an error while playing the sound... The fiddle you have given me also gave the same error. Below is **console output** `ProgressEvent now playing a sound, that starts with Uint8Array[10] failed to decode: null` – Anand N Jun 06 '14 at 09:07
  • Maybe you're trying to load some file format that isn't supported? Not all browsers (on all platforms) support all audio formats. As I said: I tested this fiddle in Chrome and Firefox (29 and Nightly) on OSX 10.9 and it works for me. – nmaier Jun 06 '14 at 09:13
  • Oh no, I get the problem, I tried playing an mp3 file and ogg file. They seem to be corrupt. I download from the same site where i was trying to find some audio context examples... I was trying so many alternatives, thinking some problem with the code, it just wasted my whole day... I will try playing some other file and see if it works... – Anand N Jun 06 '14 at 09:17
  • Yup, with some other file it works... So bad I feel :( Thanks nmaier for your time, highly appreciate it – Anand N Jun 06 '14 at 09:18
  • This drove me nuts. Finally I found that you can't access the array buffer in the result directly. instead data = new Uint8Array(reader.result) takes care of it. – bobbdelsol Sep 28 '17 at 17:42