Microphone Audio Visualizer JavaScript

Microphone Audio Visualizer JavaScript
Code Snippet:Mic Audio Visualization
Author: Benjamin Falk
Published: May 2, 2024
Last Updated: May 2, 2024
Downloads: 53
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code creates a microphone audio visualizer. It initializes visual elements and connects to the microphone stream. The visualizer displays frequency data in real-time, creating a dynamic visual effect. It helps understand audio input visually, like music visualization or voice modulation.

You can use this code on any website to add a cool audio visualizer feature. It enhances user experience by making audio interactions visually engaging. It’s perfect for music streaming platforms, podcasts, or personal websites to showcase audio content.

How to Create Microphone Audio Visualizer JavaScript

1. Start by adding the necessary HTML elements to your webpage. You need a <main> element to contain the visualizer and a button to start the visualization process. Here’s an example:

<main>
  <button onclick="init()">start</button>
</main>

2. Next, add CSS styles to make your visualizer look appealing. You can customize the styles according to your website’s design. Here’s a basic example to get you started:

*,
*::before,
*::after {
  box-sizing: border-box;
}

main {
  margin: 0;
  padding: 0;
  min-width: 100%;
  min-height: 100vh;
  font-family: sans-serif;
  text-align: center;
  color: #fff;
  background: #000 !important;
}
button {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 5em;
  height: 2em;
  margin-left: -2.5em;
  margin-top: -1em;
  z-index: 100;
  padding: 0.25em 0.5em;
  color: #fff;
  background: #000;
  border: 1px solid #fff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1.15em;
  font-weight: 200;
  box-shadow: 0 0 10px rgba(255, 255, 255, 0.5);
  transition: box-shadow 0.5s;
}
button:hover {
  box-shadow: 0 0 30px 5px rgba(255, 255, 255, 0.75);
}
main {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
main > div {
  display: inline-block;
  width: 3px;
  height: 100px;
  margin: 0 7px;
  background: currentColor;
  transform: scaleY(0.5);
  opacity: 0.25;
}
main.error {
  color: #f7451d;
  min-width: 20em;
  max-width: 30em;
  margin: 0 auto;
  white-space: pre-line;
}

3. Finally, include the following JavaScript code in your project. This code sets up the audio visualizer functionality using the Web Audio API. It initializes the visual elements and connects to the microphone stream.

class AudioVisualizer {
  constructor(audioContext, processFrame, processError) {
    this.audioContext = audioContext;
    this.processFrame = processFrame;
    this.connectStream = this.connectStream.bind(this);
    navigator.mediaDevices.getUserMedia({ audio: true, video: false }).
    then(this.connectStream).
    catch(error => {
      if (processError) {
        processError(error);
      }
    });
  }

  connectStream(stream) {
    this.analyser = this.audioContext.createAnalyser();
    const source = this.audioContext.createMediaStreamSource(stream);
    source.connect(this.analyser);
    this.analyser.smoothingTimeConstant = 0.5;
    this.analyser.fftSize = 32;

    this.initRenderLoop(this.analyser);
  }

  initRenderLoop() {
    const frequencyData = new Uint8Array(this.analyser.frequencyBinCount);
    const processFrame = this.processFrame || (() => {});

    const renderFrame = () => {
      this.analyser.getByteFrequencyData(frequencyData);
      processFrame(frequencyData);

      requestAnimationFrame(renderFrame);
    };
    requestAnimationFrame(renderFrame);
  }}


const visualMainElement = document.querySelector('main');
const visualValueCount = 16;
let visualElements;
const createDOMElements = () => {
  let i;
  for (i = 0; i < visualValueCount; ++i) {
    const elm = document.createElement('div');
    visualMainElement.appendChild(elm);
  }

  visualElements = document.querySelectorAll('main div');
};
createDOMElements();

const init = () => {
  // Creating initial DOM elements
  const audioContext = new AudioContext();
  const initDOM = () => {
    visualMainElement.innerHTML = '';
    createDOMElements();
  };
  initDOM();

  // Swapping values around for a better visual effect
  const dataMap = { 0: 15, 1: 10, 2: 8, 3: 9, 4: 6, 5: 5, 6: 2, 7: 1, 8: 0, 9: 4, 10: 3, 11: 7, 12: 11, 13: 12, 14: 13, 15: 14 };
  const processFrame = data => {
    const values = Object.values(data);
    let i;
    for (i = 0; i < visualValueCount; ++i) {
      const value = values[dataMap[i]] / 255;
      const elmStyles = visualElements[i].style;
      elmStyles.transform = `scaleY( ${value} )`;
      elmStyles.opacity = Math.max(.25, value);
    }
  };

  const processError = () => {
    visualMainElement.classList.add('error');
    visualMainElement.innerText = 'Please allow access to your microphone in order to see this demo.\nNothing bad is going to happen... hopefully :P';
  };

  const a = new AudioVisualizer(audioContext, processFrame, processError);
};

Feel free to customize the visualizer according to your preferences. You can adjust the number of visual elements, change colors, or modify animations to match your website’s style.

That’s all! hopefully, you have successfully created Microphone Audio Visualizer using JavaScript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment