0

我正在尝试实现 FileReader API 来读取音频文件,但是该脚本从未达到过它看起来的那一点。我的功能在下面,麻烦就在reader.onload = handleReaderLoad;眼前。

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));
}

在控制台中,阅读器显示 onload 事件为正在function handleReaderLoad(evt) {调用,但readeraudioSrcreader.readAsDataURL(file)变量从未记录在控制台中。我错过了什么?

4

1 回答 1

1

我已经弄清楚 FileReader API 希望如何设置事件。使用 FileReader 的主要过程是创建 FileReader,然后声明其任何/所有事件,例如 onload 或 onloadend 事件,如下所示。该过程也可以浓缩为一个主要功能。

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);
}

该函数通过创建一个 FileReader 来工作,然后通过返回该函数声明其 onload 事件,并通过在函数末尾读入数据为阅读器提供内容,在本例中是使用该readAsDataURL()方法。

于 2013-07-02T05:54:32.747 回答