Skip to content

Instantly share code, notes, and snippets.

@cho45
Created April 17, 2015 04:56
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 cho45/e2a21d733cb42e11e5a4 to your computer and use it in GitHub Desktop.
Save cho45/e2a21d733cb42e11e5a4 to your computer and use it in GitHub Desktop.
var DTMF = function () { this.init.apply(this, arguments) };
DTMF.prototype = {
table : {
"1" : [697, 1209], "2" : [697, 1336], "3" : [697, 1477], "A" : [697, 1633],
"4" : [770, 1209], "5" : [770, 1336], "6" : [770, 1477], "B" : [770, 1633],
"7" : [852, 1209], "8" : [852, 1336], "9" : [852, 1477], "C" : [852, 1633],
"*" : [941, 1209], "0" : [941, 1336], "#" : [941, 1477], "D" : [941, 1633]
},
init : function (context, opts) {
this.context = context || new AudioContext();
this.sendingTime = 100e-3;
this.minimumPause = 60e-3;
// sine を2個合成するので、半分にしとかないとクリッピングして歪みます
this.gain = this.context.createGain();
this.gain.gain.value = 0.5;
this.gain.connect(this.context.destination);
},
play : function (str) {
str = str.toUpperCase().replace(/-/g, '');
if (!str.match(/^[1234567890ABCD*#]*$/)) throw "invalid string";
this.nodes = [];
var pos = this.context.currentTime;
for (var i = 0, len = str.length; i < len; i++) {
var tone = this.table[str.charAt(i)];
var oscLow = this.context.createOscillator();
oscLow.frequency.value = tone[0];
oscLow.connect(this.gain);
var oscHigh = this.context.createOscillator();
oscHigh.frequency.value = tone[1];
oscHigh.connect(this.gain);
oscLow.start(pos);
oscHigh.start(pos);
pos += this.sendingTime;
oscLow.stop(pos);
oscHigh.stop(pos);
this.nodes.push([ oscLow, oscHigh ]); // retain
pos += this.minimumPause;
}
return pos - this.context.currentTime;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment