cryptalk/public/js/lib/audio.js

88 lines
2.1 KiB
JavaScript
Raw Permalink Normal View History

2014-09-23 13:54:36 -04:00
/* Usage:
2014-09-26 08:46:35 -04:00
mediator.on('audio:play', playTones );
mediator.on('audio:on', on );
mediator.on('audio:off', off );
mediator.on('audio:mute', mute );
mediator.on('audio:unmute', unmute );
2014-09-23 13:54:36 -04:00
*/
// Sounds module, used for emitting those annoying bl-up sounds when receiving a message
2014-09-26 08:46:35 -04:00
define(['queue','castrato','templates'], function (queue,mediator,templates) {
2014-09-23 13:54:36 -04:00
2014-09-26 08:46:35 -04:00
var
// Private variables
ac = false,
2014-09-23 13:54:36 -04:00
enabled = true,
2014-09-26 08:46:35 -04:00
muted = false,
2014-09-23 13:54:36 -04:00
2014-09-26 08:46:35 -04:00
// Recursive function for playing tones
// accepts an array of [tone,start_ms,duration_ms] - entries
2014-09-23 13:54:36 -04:00
playTones = function (tones, i) {
2014-09-26 08:46:35 -04:00
2014-09-23 13:54:36 -04:00
// Parameter defaults
i = (i === undefined) ? 0 : i;
2014-09-26 08:46:35 -04:00
// Stop if we've reached the end of iteration, and require ac, also stop if we're muted
if (!ac || !enabled || !(i < Object.keys(tones).length) || muted) {
2014-09-24 11:20:20 -04:00
return;
}
2014-09-23 13:54:36 -04:00
// Add tones to execution queue
2017-02-22 17:09:50 -05:00
var current_tones = tones[i],
freqs = current_tones[0],
start = current_tones[1],
duration = current_tones[2];
2014-09-23 13:54:36 -04:00
var o = ac.createOscillator();
var g = ac.createGain();
o.frequency.value = freqs;
o.connect(g);
g.gain.value = 0.25;
g.connect(ac.destination);
2015-12-29 18:42:00 -05:00
queue.add_function_delayed(start,function() { o.noteOn ? o.noteOn(0) : o.start(0); });
queue.add_function_delayed(start+duration,function() { o.noteOff ? o.noteOff(0) : o.stop(0); });
2014-09-23 13:54:36 -04:00
// 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-26 08:46:35 -04:00
},
mute = function() {
muted = true;
mediator.emit('console:info',templates.messages.muted);
},
unmute = function() {
muted = false;
mediator.emit('console:info',templates.messages.unmuted);
2014-09-23 13:54:36 -04:00
};
2017-02-22 17:09:50 -05:00
// Find audio context
2014-09-24 11:20:20 -04:00
if (window.AudioContext || window.webkitAudioContext) {
ac = new (window.AudioContext || window.webkitAudioContext);
}
2014-09-26 08:46:35 -04:00
2017-02-22 17:09:50 -05:00
// Connect events
2014-09-26 08:46:35 -04:00
mediator.on('audio:play', function(tones) {playTones(tones); } );
mediator.on('audio:on', on );
mediator.on('audio:off', off );
mediator.on('audio:mute', mute );
mediator.on('audio:unmute', unmute );
2014-09-23 13:54:36 -04:00
});