Skip to content

Instantly share code, notes, and snippets.

@kevincennis
Last active August 8, 2021 21:57
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kevincennis/6149078 to your computer and use it in GitHub Desktop.
Save kevincennis/6149078 to your computer and use it in GitHub Desktop.
dB meters
// see http://jsbin.com/ovewod/2/edit
var src
, fftSize = 1024
, ac = new webkitAudioContext()
, analyser = ac.createAnalyser()
, timeData = new Uint8Array(fftSize)
, bar = document.querySelector('.bar');
analyser.fftSize = fftSize;
navigator.webkitGetUserMedia({audio: true}, function( stream ) {
src = ac.createMediaStreamSource(stream);
src.connect(analyser);
analyser.connect(ac.destination);
src.connect(ac.destination);
draw();
}, function( e ) {
throw e;
});
function draw() {
var total = i = 0
, percentage
, float
, rms
, db;
analyser.getByteTimeDomainData(timeData);
while ( i < fftSize ) {
float = ( timeData[i++] / 0x80 ) - 1;
total += ( float * float );
}
rms = Math.sqrt(total / fftSize);
db = 20 * ( Math.log(rms) / Math.log(10) );
// sanity check
db = Math.max(-48, Math.min(db, 0));
percentage = 100 + ( db * 2.083 );
bar.style.width = percentage + '%';
webkitRequestAnimationFrame(draw);
}
// see http://jsbin.com/okoxiq/3/edit
var src
, fftSize = 1024
, audio = new Audio()
, ac = new webkitAudioContext()
, analyser = ac.createAnalyser()
, timeData = new Uint8Array(fftSize)
, bar = document.querySelector('.bar')
, url = 'http://static1.kevincennis.com/sounds/callmemaybe.mp3';
analyser.fftSize = fftSize;
audio.src = url;
audio.addEventListener('canplaythrough', function() {
src = ac.createMediaElementSource(audio);
src.connect(analyser);
analyser.connect(ac.destination);
src.connect(ac.destination);
audio.play();
draw();
}, false);
function draw() {
var total = i = 0
, percentage
, float
, rms
, db;
analyser.getByteTimeDomainData(timeData);
while ( i < fftSize ) {
float = ( timeData[i++] / 0x80 ) - 1;
total += (float * float);
}
rms = Math.sqrt(total / fftSize);
db = 20 * ( Math.log(rms) / Math.log(10) );
// sanity check
db = Math.max(-48, Math.min(db, 0));
percentage = 100 + ( db * 2.083 );
bar.style.width = percentage + '%';
webkitRequestAnimationFrame(draw);
}
@JerryCjr
Copy link

what is 0x80 mean

@the-stas
Copy link

the-stas commented Aug 4, 2019

@JerryCjr it means the following value is in hexadecimal

@JerryCjr
Copy link

JerryCjr commented Aug 7, 2019

ok, thanks. And i also want to confirm whether the decibels calculated is the same as 'ffmpeg'.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment