gpt4 book ai didi

JavaScript 网络音频 : cannot properly decode audio data?

转载 作者:行者123 更新时间:2023-11-28 04:33:23 25 4
gpt4 key购买 nike

我正在尝试使用 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 everything 直到你确切地知道它在任何时候的行为。

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


}

关于JavaScript 网络音频 : cannot properly decode audio data?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26447932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com