Created
March 4, 2016 23:33
-
-
Save autonome/8e4cdc2c0510040db5a8 to your computer and use it in GitHub Desktop.
average volume reporter
This file contains 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 start() { | |
navigator.mediaDevices.getUserMedia({ audio: true}) | |
.then(onMediaStreamHandler) | |
.catch(function(error) { | |
console.log('getUserMedia error: ', err); | |
}); | |
} | |
function onMediaStreamHandler(stream) { | |
stream.onactive = function(e) { console.log('stream active', e) }; | |
stream.onaddtrack = function(e) { console.log('stream track added', e) }; | |
stream.onended = function(e) { console.log('stream ended', e) }; | |
stream.oninactive = function(e) { console.log('stream inactive', e) }; | |
stream.onremovetrack = function(e) { console.log('stream track removed', e) }; | |
var audioCtx = new AudioContext(); | |
var analyser = audioCtx.createAnalyser(); | |
analyser.minDecibels = -90; | |
analyser.maxDecibels = -10; | |
analyser.smoothingTimeConstant = 0.85; | |
var source = audioCtx.createMediaStreamSource(stream); | |
source.connect(analyser); | |
var gainNode = audioCtx.createGain(); | |
gainNode.connect(audioCtx.destination); | |
var bufferLength = analyser.fftSize; | |
var dataArray = new Uint8Array(analyser.frequencyBinCount); | |
var rAFHandle = null, | |
avgVolume = 0, | |
lastVolume = 0; | |
(function draw() { | |
rAFHandle = requestAnimationFrame(draw); | |
analyser.getByteFrequencyData(dataArray); | |
avgVolume = getAverageVolume(dataArray); | |
})(); | |
setInterval(function() { | |
console.log('avgvol', avgVolume) | |
lastVolume = avgVolume | |
}, 1000); | |
function getAverageVolume(data) { | |
return data.reduce(function(sum, value){ | |
return sum + value; | |
}, 0) / data.length; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment