JavaScript Web音频:无法正确解码音频数据



我正在尝试使用JavaScript中的Web Audio API将声音加载到缓冲区并播放。不幸的是,它不起作用,我得到以下错误:

Uncaught TypeError: Failed to set the 'buffer' property on 'AudioBufferSourceNode':
The provided value is not of type 'AudioBuffer'.

我可以准确地指出是哪条线给了我错误,但我不知道为什么。如果有帮助的话,下面是相关代码:

var audioContext;
var playSoundBuffer;
function init() {
    window.AudioContext = window.AudioContext || window.webkitAudioContext;
    audioContext = new AudioContext();
    loadNote();
}
function loadNote() {
    var request = new XMLHttpRequest();
    request.open("GET", "./sounds/topE.wav", true);
    request.responseType = "arraybuffer";
    request.onload = function() {
        audioContext.decodeAudioData(request.response, function(buffer) {
            playSoundBuffer = buffer;
        }, function(error) {
            console.error("decodeAudioData error", error);
        });
    };
    request.send();
    playSound();
}
function playSound() {
    var source = audioContext.createBufferSource();
    source.buffer = playSoundBuffer;       // This is the line that generates the error
    source.connect(audioContext.destination);
    source.start(0);
}

我相信decodeAudioData方法会将AudioBuffer返回给它的第一个回调函数(它的第二个参数)。我试图将这个AudioBuffer保存到"playSoundBuffer"中,然后播放它,但我遇到了错误,我不知道为什么。如有任何帮助,我们将不胜感激。

出现该错误的原因是您忽略了代码的异步特性,并将其视为同步代码。如果在调试的第一步中始终记录所有相关部分的内容,您会意识到,在尝试处理缓冲区时,它是undefined,而不是AudioBuffer。提示:始终console.log所有东西,直到您确切了解它在任何时候的行为。

function loadNote() {
    var request = new XMLHttpRequest();
    request.open("GET", "./sounds/topE.wav", true);
    request.responseType = "arraybuffer";
    request.onload = function() {
        audioContext.decodeAudioData(request.response, function(buffer) {
            playSoundBuffer = buffer;
            playSound(); // don't start processing it before the response is there!
        }, function(error) {
            console.error("decodeAudioData error", error);
        });
    };
    request.send();//start doing something async

}

最新更新