0

I am trying to implement the FileReader API to read an audio file, but the script never gets to that point from what it seems. My function is below and the trouble is at the reader.onload = handleReaderLoad; line.

function setupFS(file) {
    console.log('setupFS function entered.');
    var reader = new FileReader();
    console.log(reader);
    reader.onload = handleReaderLoad;
}

function handleReaderLoad(evt) {
    console.log(reader);
    var audioSrc = $('.file-playlist table tr:nth-child(n+1) td:first-child');
    console.log(audioSrc);
    console.log(reader.readAsDataURL(file));
    audioSrc.attr('data-src', reader.readAsDataURL(file));
}

In the console, the reader shows up with the onload event as having a function handleReaderLoad(evt) { call, but the reader, audioSrc, and reader.readAsDataURL(file) variables are never logged in the console. What am I missing?

1 Answer 1

1

I've figured out how the FileReader API wants the events to be set up. The main process of using a FileReader works by creating a FileReader, then declaring any/all of its events such as the onload or the onloadend events which are shown below. The process can also be condensed into one main function.

function readFile(file) {
    var audioSrc;
    audioSrc = $('.file-playlist table tr:nth-child(' + n + ') td:first-child');
    var progress = $('.file-playlist table tr:nth-child(' + n + ') td:last-child progress');
    n++;
    progress.removeAttr('value');
    progress.attr('data-mod', 'true');
    var reader = new FileReader();
    reader.onload = (function(file) {
        return function(e) {
            audioSrc.attr('data-src', e.target.result);
            $('.file-playlist audio source').attr('data-src', e.target.result);
            progress.attr('value', '100');
            console.log('onload stage finished');
        };
    })(file);
    reader.onloadend = (function() {
        audioSrc.text(file.name);
    });
    reader.readAsDataURL(file);
}

The function works by creating a FileReader, then declaring its onload events by returning the function, and the reader is given content by reading in data at the end of the function, in this case by using the readAsDataURL() method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.