diff --git a/hark.js b/hark.js index 2cda214..0c7e2b5 100644 --- a/hark.js +++ b/hark.js @@ -30,6 +30,7 @@ module.exports = function(stream, options) { interval = (options.interval || 100), threshold = options.threshold, play = options.play, + history = options.history || 10, running = true; //Setup Audio Context @@ -76,6 +77,10 @@ module.exports = function(stream, options) { harker.emit('stopped_speaking'); } }; + harker.speakingHistory = []; + for (var i = 0; i < options.history; i++) { + harker.speakingHistory.push(0); + } // Poll the analyser node to determine if speaking // and emit events if changed @@ -91,6 +96,29 @@ module.exports = function(stream, options) { harker.emit('volume_change', currentVolume, threshold); + var history = 0; + if (currentVolume > threshold && !harker.speaking) { + // trigger quickly, short history + for (var i = harker.speakingHistory.length - 3; i < harker.speakingHistory.length; i++) { + history += harker.speakingHistory[i]; + } + if (history >= 2) { + harker.speaking = true; + harker.emit('speaking'); + } + } else if (currentVolume < threshold && harker.speaking) { + for (var i = 0; i < harker.speakingHistory.length; i++) { + history += harker.speakingHistory[i]; + } + if (history == 0) { + harker.speaking = false; + harker.emit('stopped_speaking'); + } + } + //console.log((new Date()).getTime(), history, harker.speakingHistory); + harker.speakingHistory.shift(); + harker.speakingHistory.push(0 + (currentVolume > threshold)); + if (currentVolume > threshold) { if (!harker.speaking) { harker.speaking = true;