Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
143
rated 0 times [  149] [ 6]  / answers: 1 / hits: 18600  / 10 Years ago, sun, october 19, 2014, 12:00:00

I'm trying to use the Web Audio API in JavaScript to load a sound into a buffer and play it. Unfortunately it doesn't work and I get the following error:



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


I can pinpoint which line is giving me the error, but I don't know why. Here is the relevant code if it helps:



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);
}


I believe the decodeAudioData method returns an AudioBuffer to its first callback function (its second parameter). I tried to save this AudioBuffer to the playSoundBuffer and then play it, but I get that error and I'm not sure why. Any help would be greatly appreciated.


More From » html

 Answers
59

The reason you get that error is because you are ignoring the asynchronous nature of your code and treat it as if it were synchronous. If you always log the contents of all relevant parts as the first step in debugging you will realize that at the time you try to process your buffer it's undefined and not an AudioBuffer at all. Tip: Always console.log everything until you know exactly how it behaves at any point.



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


}

[#69083] Wednesday, October 15, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kiley

Total Points: 733
Total Questions: 118
Total Answers: 94

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
;