Skip to content

Instantly share code, notes, and snippets.

@kevlened
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevlened/ce040c88a8c65e5a2d9f to your computer and use it in GitHub Desktop.
Save kevlened/ce040c88a8c65e5a2d9f to your computer and use it in GitHub Desktop.
A stopwatch that starts and stop by voice - http://jsfiddle.net/7bmjyve2/
<html>
<head>
<title>Microphone Stopwatch</title>
</head>
<body>
<div id="time"></div>
<script type='text/javascript'>
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var lastSnap = 0;
var timeEl = document.getElementById('time');
navigator.getUserMedia = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
if(navigator.getUserMedia) {
timeEl.innerText = "Clap or yell to start the stopwatch";
navigator.getUserMedia({audio: true}, function(stream) {
// Build nodes
var source = audioCtx.createMediaStreamSource(stream);
var script = audioCtx.createScriptProcessor(256, 1, 1);
var gain = audioCtx.createGain();
// Configure nodes
gain.gain.value = 0; // Must include muting for scripting to work
script.onaudioprocess = function(e) {
// Check if volume is about a certain level
var input = e.inputBuffer;
var inputData = input.getChannelData(0);
// Loop through the samples
for (var sample = 0; sample < input.length; sample++) {
if(Date.now() - lastSnap > 400 && Math.abs(inputData[sample]) > 0.04) {
console.log('snap');
flipStopwatch();
lastSnap = Date.now();
break;
}
}
}
// Chain nodes
source.connect(script);
script.connect(gain);
gain.connect(audioCtx.destination);
}, function (err) {
console.log('The following error occured: ' + err);
})
} else {
timeEl.innerText = "Microphones aren't supported in this browser."
}
var startTime;
var clock;
function flipStopwatch() {
if(clock) {
stopStopwatch();
} else {
startStopwatch();
}
}
function startStopwatch() {
startTime = Date.now();
updateTime();
clock = setInterval(updateTime, 15);
}
function stopStopwatch() {
clearInterval(clock);
clock = null;
}
function updateTime() {
timeEl.innerText = ((Date.now() - startTime)/1000).toFixed(3);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment