'Noise Reduction - Pitchy JS

I have this code which takes live audio of microphone, converts it into frequency and finally displays the time vs frequency graph. It is working fine.

What I need to do? While I am taking audio from the microphone there is noise in the recorded audio which is fluctuating the frequency.

I need to remove / reduce that noise/background disturbance and get a little bit more smoothed output - audio frequency.

CODE

import { PitchDetector } from "https://esm.sh/pitchy@3";

function updatePitch(analyserNode, detector, input, sampleRate) {
    analyserNode.getFloatTimeDomainData(input);
    const [pitch, clarity] = detector.findPitch(input, sampleRate);

    
    Plotly.extendTraces('chart', {y: [[Math.round(pitch * 10) / 10]]}, [0])
        
    document.getElementById("pitch").textContent = `${Math.round(pitch * 10) / 10
        } Hz`;
    document.getElementById("clarity").textContent = `${Math.round(
        clarity * 100
    )} %`;
    window.setTimeout(
        () => {
            updatePitch(analyserNode, detector, input, sampleRate);
        },
        250
    );
}

Plotly.plot(
    'chart', [{
        y: [Math.round(pitch * 10) / 10],
        type: 'line'
    }]
);

document.addEventListener("DOMContentLoaded", () => {
    const audioContext = new window.AudioContext();
    const analyserNode = audioContext.createAnalyser();

    document
        .getElementById("resume-button")
        .addEventListener("click", () => audioContext.resume());

    navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
        audioContext.createMediaStreamSource(stream).connect(analyserNode);
        const detector = PitchDetector.forFloat32Array(analyserNode.fftSize);
        const input = new Float32Array(detector.inputLength);
        updatePitch(analyserNode, detector, input, audioContext.sampleRate);
    });
});


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source