Make a Microphone Tester Using HTML, CSS and JavaScript


This is the tool you are going to make after reading this article.

What is a microphone tester?

A microphone tester is a software or tool that helps to test microphone conditions like is it working or not, or has some problem. The working process is simple. Just take the signal from the microphone and then show statistics according to that signal.

mic test

Your device takes electronic signals from the microphone, headset, earphone, or any device that has the functionality. Then the internal processing units process those signals and give output or store it in digital format.

A microphone tester does that same process to detect that the mic is working or not. This tool should have some functions that can trigger in some specific cases. Like if the mic is not connected with the device then a function that will execute will do something like showing any custom error message or warning. The main goal of this software is, help users to find out the problems and provide a way to fix them.

How to make a microphone tester

To make a Microphone Tester you need to understand basic technology like core data handling. Taking information directly from the CPU is not so easy for beginners. So, in this tutorial, we are going to use the easy method to do that. At first, take a look at the codes. First, create a folder on your computer and open it in vs code or any code editor you like.

Then create 3 files which are for HTML, CSS, and JavaScript. I am giving them the name which is index.html, style.css, mic.js. Here is the HTML code you have to paste into the HTML file.

HTML code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Microphone Test</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
    <div class="bar" id="volume-visualizer"></div>
    <div class="components">
        <button class="techkib-online-tool-button" id="start">
            <i class="fa fa-microphone"></i> Start The Test
        </button>
        <button class="techkib-online-tool-button" id="stop"><i class="fa fa-stop"></i> Stop</button>
        <button class="techkib-online-tool-button" onClick="window.location.reload();">
            <i class="fa fa-refresh"> </i> Reload Test Environment
        </button>
    </div>
    <h3 id="tex"></h3>
</body>
<script src="mic.js"></script>
</html>

Here we are using the font-awesome library to use nice font and icons. We also inked the CSS file and JavaScript in this file. Next, you have to copy the CSS code below and paste it into the CSS file.

CSS code

.bar {
    --volume: 0%;
    position: relative;
    width: 100%;
    height: 50px;
    border-radius: 5px;
    margin-bottom: 20px;
}

.bar::before {
    content: '';
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    border-radius: 5px;
    width: var(--volume);
    background-color: green;
    transition: width 100ms linear;
}

.techkib-online-tool-button {
    background-color: black;
    border: none;
    border-radius: 5px;
    color: yellow;
    padding: 12px 16px;
    font-size: 16px;
    cursor: pointer;
    outline: none;
    margin-top: 5px;
    margin-bottom: 5px;
    margin-left: 5px;
    margin-right: 5px;
}

Here we created the volume bar and button. We need to change the size of the volume bar and button for better visibility. Then you have to paste the JavaScript code into the js file.

JavaScript Code

(async () => {
    let volumeCallback = null;
    let volumeInterval = null;
    const volumeVisualizer = document.getElementById('volume-visualizer');
    const startButton = document.getElementById('start');
    const stopButton = document.getElementById('stop');
    try {
        const audioStream = await navigator.mediaDevices.getUserMedia({
            audio: {
                echoCancellation: true
            }
        });
        const audioContext = new AudioContext();
        const audioSource = audioContext.createMediaStreamSource(audioStream);
        const analyser = audioContext.createAnalyser();
        analyser.fftSize = 512;
        analyser.minDecibels = -127;
        analyser.maxDecibels = 0;
        analyser.smoothingTimeConstant = 0.4;
        audioSource.connect(analyser);
        const volumes = new Uint8Array(analyser.frequencyBinCount);
        volumeCallback = () => {
            analyser.getByteFrequencyData(volumes);
            let volumeSum = 0;
            for (const volume of volumes)
                volumeSum += volume;
            const averageVolume = volumeSum / volumes.length;
            volumeVisualizer.style.setProperty('--volume', (averageVolume * 100 / 127) + '%');
            var taxi;
            taxi = document.getElementById("tex");
            taxi.innerHTML = "Your Microphone is Working! 😇";
        };
    }
    catch (e) {
        console.error('Failed to initialize volume visualizer, simulating instead...', e);
        let lastVolume = 50;
        volumeCallback = () => {
            const volume = Math.min(Math.max(Math.random() * 100, 0.8 * lastVolume), 1.2 * lastVolume);
            lastVolume = volume;
            volumeVisualizer.style.setProperty('--volume', volume + '%');
            var taxi;
            taxi = document.getElementById("tex");
            taxi.innerHTML = "Status: Microphone is not working! ❌";
        };
    }
    startButton.addEventListener('click', () => {
        if (volumeCallback !== null && volumeInterval === null)
            volumeInterval = setInterval(volumeCallback, 100);
    });
    stopButton.addEventListener('click', () => {
        if (volumeInterval !== null) {
            clearInterval(volumeInterval);
            volumeInterval = null;
        }
    });
})();

Now go to the HTML file and open it in the live server or you can go to the folder and click on the HTML file. It will open in the browser. It is a web-based application so you need a decent browser like Chrome, Firefox. The first time it will ask for Microphone access. If a user gives it permission then it can use that to show the analysis report.

There is some problem you can face. Sometimes outdated browsers don't respond because we used the WebRTC in this project. Make sure your browser is updated and has no internal errors.

Use Cases

You can use this directly on your website to help your visitors or you can use the technology in your project. Also, this can be a great project for you GitHub. Make a GitHub page and share it with your friends. You can also create a tool website with is.

4 Comments

Post a Comment
Previous Post Next Post