I'm experimenting with the Web Audio API to visualize a simple sine wave (A4 at 440 Hz). However, when I try to read frequency data from the AnalyserNode
, the array always returns all zero values, even though the oscillator is playing. I expected some non-zero values in the array.
Below is my example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Web Audio Analyser Issue</title>
</head>
<body>
<button id="start">Start Analyzer</button>
<button id="stop">Stop Analyzer</button>
<div id="log"></div>
<script>
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const oscillator = audioCtx.createOscillator();
const analyser = audioCtx.createAnalyser();
oscillator.frequency.value = 440;
oscillator.connect(analyser).connect(audioCtx.destination);
document.getElementById('start').addEventListener('click', () => {
oscillator.start();
//read frequecy data
const dataArray = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(dataArray);
console.log('Frequency data:', dataArray);
document.getElementById('log').textContent = 'Frequency data: ' + dataArray;
});
document.getElementById('stop').addEventListener('click', () => {
oscillator.stop();
});
</script>
</body>
</html>