Created
November 7, 2014 06:40
-
-
Save nw/0d4018ae6ae3ea4ef4ba 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
var tessel = require('tessel') | |
, fs = require('fs') | |
, ambient = require('ambient-attx4').use(tessel.port['A']) | |
, audio = require('audio-vs1053b').use(tessel.port['D']); | |
var audioFile = fs.readFileSync('sample.mp3') // load mp3 into memory (small 29kb - 2.5 secs) | |
, timeout = 1000 * 60 // how long to wait after trigger and actions have happened. | |
, threshold = .2 // ambient noise trigger | |
, queue = 2; // number of modules to wait for | |
ambient.on('ready', dequeue); | |
audio.on('ready', setVolume); | |
function watch () { | |
console.log('ready and listening'); | |
var IntervalId = setInterval(function(){ | |
ambient.getSoundLevel( function(err, sdata) { | |
console.log('getting sound level', sdata); | |
if(err) return error(err); | |
if(sdata >= threshold) { | |
console.log('triggered'); | |
clearInterval(IntervalId); | |
setTimeout(action, 1000); // tried adding timeout here... made no difference | |
} | |
}); | |
}, 1000); | |
} | |
function action (){ | |
console.log('playing audio'); | |
audio.play(audioFile, function(err){ // this sounds like crap... choppy small clips... never waited for it to complete. Minutes? | |
console.log('done playing'); // script never gets to this line | |
if(err) error(err); | |
audio.stop(function(err){ | |
if(err) error(err); | |
console.log('reseting audio'); | |
setTimeout(watch, timeout); // done handling trigger, go back to listening | |
}) | |
}); | |
} | |
function dequeue() { | |
if(--queue <= 0) watch(); | |
} | |
function setVolume(){ | |
console.log('adjusting volume'); | |
audio.setVolume(10, function(err){ | |
if(err) error(err); | |
dequeue(); | |
}) | |
} | |
function error(err){ | |
console.error("ERROR: ", err); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment