未捕获的TypeError:值不是AudioBuffer类型的 [英] Uncaught TypeError: Value is not of type AudioBuffer

查看:109
本文介绍了未捕获的TypeError:值不是AudioBuffer类型的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试运行XHR加载样本时出现此错误.未捕获到的TypeError:值不是AudioBuffer类型.一切似乎都是正确的,但我不确定是什么问题.

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

我从请求开始:

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

}

然后我尝试运行它.

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

推荐答案

问题是kit.load()会触发异步请求以加载和解码音频缓冲区.无论是否已加载文件,后面的两行(createBufferSource,分配缓冲区)都会立即跟随异步请求.因此,得到此值不是AudioBuffer类型"的原因是,在分配voice.buffer = kit.snareBuffer时,kit.snareBuffer仍未定义,因为未触发加载回调.

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.

之所以可能与window.onload一起工作的原因是因为XHR请求可以在加载窗口之前运行,这意味着在触发window.onload事件处理程序时,XHR请求已经返回并且是已定义的audioBuffer.

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!

这篇关于未捕获的TypeError:值不是AudioBuffer类型的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆