Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple code to calculate frequency of Live Mic Audio using WebAudio API

I have website in which I need to display the frequency of the Live Mic Audio. I have a this code, but its extremely difficult to understand (It uses Fourier Transform and all). On some research I got to know of getByteFrequencyData() which returns the frequency of the audio. Has anyone used it before with Live Mic Audio preferably in Web Audio API?

like image 373
FlyingAura Avatar asked Apr 16 '14 15:04

FlyingAura


1 Answers

I write a simple code that you can show frequency in your webpage:

const audioCtx = new AudioContext();
const analyser = audioCtx.createAnalyser();
const source = audioCtx.createMediaElementSource(audio);

source.connect(analyser);
analyser.connect(audioCtx.destination);
analyser.fftSize = 32;

let frequencyData = new Uint8Array(analyser.frequencyBinCount);

function renderFrame() {
    analyser.getByteFrequencyData(frequencyData);
    P10.style.height = ((frequencyData[0] * 100) / 256) + "%";
    P20.style.height = ((frequencyData[1] * 100) / 256) + "%";
    P30.style.height = ((frequencyData[2] * 100) / 256) + "%";
    P40.style.height = ((frequencyData[3] * 100) / 256) + "%";
    P50.style.height = ((frequencyData[4] * 100) / 256) + "%";
    P60.style.height = ((frequencyData[5] * 100) / 256) + "%";
    P70.style.height = ((frequencyData[6] * 100) / 256) + "%";
    P80.style.height = ((frequencyData[7] * 100) / 256) + "%";
    P90.style.height = ((frequencyData[8] * 100) / 256) + "%";
    console.log(frequencyData)
    requestAnimationFrame(renderFrame);
}
audio.pause();
audio.play();
renderFrame();
#bar {
    position: fixed;
    top: 20%;
    left: 40%;
    width: 40%;
    height: 40%;
    -webkit-transition: 0.1s ease all;
}

.p {
    background-color: blue;
    height: 100%;
    width: 10%;
    float: left;
}
<audio id="audio" src="2.mp3"></audio>
<div id="bar">
    <div id="P10" class="p"></div>
    <div id="P20" class="p"></div>
    <div id="P30" class="p"></div>
    <div id="P40" class="p"></div>
    <div id="P50" class="p"></div>
    <div id="P60" class="p"></div>
    <div id="P70" class="p"></div>
    <div id="P80" class="p"></div>
    <div id="P90" class="p"></div>
</div>

Good luck.

like image 120
Ali Avatar answered Sep 20 '22 00:09

Ali