Skip to content

Instantly share code, notes, and snippets.

@Oobert
Forked from anonymous/jsbin.ixuyid.css
Created January 17, 2014 01:33
Show Gist options
  • Save Oobert/8466959 to your computer and use it in GitHub Desktop.
Save Oobert/8466959 to your computer and use it in GitHub Desktop.
#meter {
width: 0%;
height: 15px;
margin: 2px 0;
background: green;
-webkit-transition: width .05s;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id=meter></div>
</body>
</html>
+function(){
console.log('start-----------------------');
var ctx = new webkitAudioContext()
, url = '//geekwithopinions.com/media/test.mp3'
, audio = new Audio(url)
// 2048 sample buffer, 1 channel in, 1 channel out
, processor = ctx.createJavaScriptNode(2048, 1, 1)
, meter = document.getElementById('meter')
, source
audio.addEventListener('canplaythrough', function(){
source = ctx.createMediaElementSource(audio)
source.connect(processor)
source.connect(ctx.destination)
processor.connect(ctx.destination)
audio.play()
}, false);
// loop through PCM data and calculate average
// volume for a given 2048 sample buffer
processor.onaudioprocess = function(evt){
var input = evt.inputBuffer.getChannelData(0)
, len = input.length
, total = i = 0
, rms
while ( i < len ) total += Math.abs( input[i++] );
rms = Math.sqrt( total / (len /2));
meter.style.width = ( rms * 100 ) + '%';
var decibel = 20 * (Math.log(rms) / Math.log(10));
//console.log(decibel, rms);
if (decibel < -5 &&
decibel != Number.NEGATIVE_INFINITY &&
!isShot){
isShot = true;
console.log('shot started', decibel);
}
if (decibel >= -5 && isShot){
isShot = false;
console.log('no shot');
}
}
var isShot = false;
}()
@Oobert
Copy link
Author

Oobert commented Jan 17, 2014

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