Created
January 17, 2014 01:32
-
-
Save anonymous/8466948 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#meter { | |
width: 0%; | |
height: 15px; | |
margin: 2px 0; | |
background: green; | |
-webkit-transition: width .05s; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset=utf-8 /> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<div id=meter></div> | |
</body> | |
</html> | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+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; | |
}() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment