1
我正嘗試在JavaScript中使用Web Audio API將聲音加載到緩衝區並播放它。遺憾的是它不工作,我得到了以下錯誤:JavaScript Web音頻:無法正確解碼音頻數據?
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」然後播放它,但是我得到了這個錯誤,我不知道爲什麼。任何幫助將不勝感激。
非常感謝您的回覆!您建議的編輯使聲音播放正常。不幸的是我不太瞭解異步函數是如何工作的。 playSound()方法是否與decodeAudioData方法同時執行?那是什麼造成了錯誤?再次感謝你的幫助! – hashahid 2014-10-19 07:36:17
這裏是一個文章https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests在你的情況下,你實際上在'decodeAudioData'方法之前執行了'playSound()'方法,基本上在您發送請求(即異步)之後,在請求到達之前,以及在您開始對其進行解碼之前(這也是異步) – Winchestro 2014-10-19 07:48:52