我正在尝试使用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”然后播放它,但我得到了这个错误,我不知道为什么。任何帮助将不胜感激。
答案 0 :(得分:7)
您收到该错误的原因是您忽略了代码的异步性质并将其视为同步。如果您始终将所有相关部件的内容记录为调试的第一步,您将意识到当您尝试处理缓冲区时,它是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
}