![](/img/trans.png)
[英]Web Audio API Inconsistent Unable to decode audio data DOMException
[英]JavaScript Web Audio: cannot properly decode audio data?
我正在嘗試使用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);
}
我相信encodeAudioData方法會將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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.