cryptalk/public/js/cryptalk_modules/audio.js

69 lines
1.7 KiB
JavaScript
Raw Normal View History

2014-09-23 13:54:36 -04:00
/* Usage:
2014-09-24 11:20:20 -04:00
mediator.emit('audio:play',message);
mediator.emit('audio:on');
mediator.emit('audio:off');
2014-09-23 13:54:36 -04:00
*/
// Sounds module, used for emitting those annoying bl-up sounds when receiving a message
define(['queue','mediator'], function (queue,mediator) {
2014-09-23 14:16:02 -04:00
var ac = false,
2014-09-23 13:54:36 -04:00
enabled = true,
// Recursive function for playing tones, takes an array of [tone,start_ms,duration_ms] - entries
// i is only used for recursion
playTones = function (tones, i) {
// Parameter defaults
i = (i === undefined) ? 0 : i;
// Stop if we've reached the end of iteration, and require ac
2014-09-24 11:20:20 -04:00
if (!ac || !enabled || !(i < Object.keys(tones).length)) {
return;
}
2014-09-23 13:54:36 -04:00
// Add tones to execution queue
var current_tones = tones[i],
freqs = current_tones[0],
start = current_tones[1],
duration = current_tones[2];
var o = ac.createOscillator();
var g = ac.createGain();
o.frequency.value = freqs;
o.connect(g);
g.gain.value = 0.25;
g.connect(ac.destination);
queue.add_function_delayed(start,function() { o.noteOn(0); });
queue.add_function_delayed(start+duration,function() { o.noteOff(0); });
// Iterate, or start playing
i++;
if( i < Object.keys(tones).length ) {
playTones(tones,i);
} else {
queue.run();
}
},
on = function() {
enabled = true;
},
off = function() {
enabled = false;
};
2014-09-24 11:20:20 -04:00
if (window.AudioContext || window.webkitAudioContext) {
ac = new (window.AudioContext || window.webkitAudioContext);
}
2014-09-23 13:54:36 -04:00
2014-09-24 11:20:20 -04:00
mediator.on('audio:play', function (message) { playTones(message); });
mediator.on('audio:on', function (message) { on(); });
mediator.on('audio:off', function (message) { off(); });
2014-09-23 13:54:36 -04:00
});