I am trying to get the fft of a wav flie. The problem is that I keep on getting infinity as my spectrum. Receiving back infinity means that there is no source connected to the analyzer. I think my problem resided in the how I am constructing the audio source in the source variable. My code is available here
<html>
<body>
<input id="fileItem" type="file">
<script>
var audioContext = new AudioContext();
//Create analyser node
const analyserNode = audioContext.createAnalyser();
analyserNode.fftSize = 256;
const bufferLength = analyserNode.frequencyBinCount;
const dataArray = new Float32Array(bufferLength);
//setup audio souce
var source = audioContext.createBufferSource();
//Set up audio node network
source.connect(analyserNode);
analyserNode.connect(audioContext.destination);
var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var arrayBuffer = reader.result;
console.log("arrayBuffer:");
console.log(arrayBuffer);
audioContext.decodeAudioData(arrayBuffer, decodedDone);
};
reader.readAsArrayBuffer(input.files[0]);
};
function decodedDone(decoded) {
// set the buffer in the AudioBufferSourceNode
source.buffer = decoded;
source.connect(analyserNode);
source.start();
//Get spectrum data
analyserNode.getFloatFrequencyData(dataArray);
console.log(dataArray)
var typedArray = new Float32Array(decoded.length);
typedArray=dataArray//decoded.getChannelData(0);
console.log("typedArray:");
console.log(typedArray);
}
document.querySelector("#fileItem").onchange= openFile
</script>
</body>
</html>
A couple of issues here. You connect source
to the analyserNode
twice. Harmless, but unnecessary.
I think the real issue is that you start the source and then immediately ask for the frequency data. There is no time allowed for the source to produce data yet, so the AnalyserNode's internal buffer is still all zeroes, so you get infinities for the output.
As a test, use a setTimeout or something to pause for a bit (try at least 10ms or so), and you should then see values that aren't all infinity.