Uncaught TypeError: Value is not of type AudioBuffer

我的未来我决定 提交于 2019-12-24 03:27:48

问题


I get this error when I try to run an XHR to load a sample. Uncaught TypeError: Value is not of type AudioBuffer. Everything seems to be right, but I'm not sure what the problem is.

Kit.prototype.load = function(){
    if(this.startedLoading)
        return;
    this.startedLoading = true;

    // var kick = "samples/M-808Sn2.wav";
    var snare = "samples/M-808Sn2.wav";
    // var hihat = "samples/M-808Sn2.wav";

    // this.loadSample(0, kick, false);
    this.loadSample(1, snare, false);
    // this.loadSample(2, hihat, false);
}

I start it off with the request:

Kit.prototype.loadSample = function(sampleID, url, mixToMono){
// Load Asynchronously

var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";

var kit = this;

request.onload = function(){

    var buffer;
    context.decodeAudioData(request.response, function(decodedBuffer){
        buffer = decodedBuffer;
    });

    switch(sampleID){
        // case 0: kit.kickBuffer = buffer; break;
        case 1: kit.snareBuffer = buffer; break;
        // case 2: kit.hihatBuffer = buffer; break;
    }
}

request.send();

}

Then I try to run it.

 context = new webkitAudioContext();


var kit = new Kit();

kit.load();

var voice = context.createBufferSource();

voice.buffer = kit.snareBuffer;
voice.loop = true;
voice.playbackRate.value = 1;
voice.connect(gain);

voice.start(0);
voice.stop(2);

回答1:


The issue is that kit.load() fires off an asynchronous request to load and decode the audio buffers. The two lines that follow (createBufferSource, assign the buffer) follow the asynchronous request immediately, whether or not the files have been loaded. So the reason you're getting this "Value is not of type AudioBuffer" is because at the time you assign voice.buffer = kit.snareBuffer, kit.snareBuffer is still undefined because the load callback hasn't fired.

The reason this probably works with window.onload is because the XHR request can run before the window has loaded, which means that by the time the window.onload event handler is fired, the XHR request has already come back and kit.snareBuffer is a defined audioBuffer.

This answer is coming a little late, but hope it helps!




回答2:


Looks like a regression in chrome. Even I am getting same error. See below chrome bug

http://code.google.com/p/chromium/issues/detail?id=128826



来源:https://stackoverflow.com/questions/14825030/uncaught-typeerror-value-is-not-of-type-audiobuffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!