AudioJS – Get Average Frequency

I’m working on a ThreeJS project, and I need to get the average Frequency of a sound to visualize audio on a mesh.

I’ve tried the THREE.Audio() and works well, but my app needs to play the Audio at the beginning and three audio doesn’t do that. So I’m working with native Audio JS, but I’m a bit lost with how to create the audio context for passing to the analyzer and get the data.

I’m trying things like this but no success

    // Create Audio Context
    const audioContext = new (window.AudioContext || window.webkitAudioContext)();

    // Create Analyser Node
    const analyser = audioContext.createAnalyser();
    Set FFT size for the analyser (higher values = more frequency bins)
    analyser.fftSize = 2048;

    // Create a buffer to store the frequency data
    const bufferLength = analyser.frequencyBinCount;

    const frequencyData = new Uint8Array(bufferLength);

    // Connect audio element to analyser
    const source = audioContext.createMediaElementSource(music);
    source.connect(analyser);

    // Connect analyser to destination
    analyser.connect(audioContext.destination);

Some links that I’ve read

https://www.reddit.com/r/learnjavascript/comments/131hlma/how_can_we_get_frequency_values_in_hertz_from_an/

https://henrypye.medium.com/reading-audio-frequency-data-using-file-uploader-in-html-web-audio-api-and-p5-js-8cd819ff9ae0

https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Visualizations_with_Web_Audio_API