-
Notifications
You must be signed in to change notification settings - Fork 0
/
morse.js
129 lines (116 loc) · 2.9 KB
/
morse.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// http://blog.theincredibleholk.org/blog/2014/06/23/generating-morse-code-with-javascript/
function MorseNode(ac, rate, farnsworth) {
// ac is an audio context.
this._oscillator = ac.createOscillator();
this._gain = ac.createGain();
this._intervals = [];
this._maxGain = 0.75;
this._gain.gain.value = 0;
this._oscillator.frequency.value = 750;
this._oscillator.type = this._oscillator.SINE;
this._oscillator.connect(this._gain);
if(rate == undefined)
rate = 20;
this._dot = 1.2 / rate; // formula from Wikipedia.
if(farnsworth == undefined)
this._space = 1.2 / rate
else
this._space = 1.2 / farnsworth
this._oscillator.start(0);
}
MorseNode.prototype.connect = function(target) {
return this._gain.connect(target);
}
MorseNode.prototype.MORSE = {
"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"I": "..",
"J": ".---",
"K": "-.-",
"L": ".-..",
"M": "--",
"N": "-.",
"O": "---",
"P": ".--.",
"Q": "--.-",
"R": ".-.",
"S": "...",
"T": "-",
"U": "..-",
'V': "...-",
"W": ".--",
"X": "-..-",
"Y": "-.--",
"Z": "--..",
"1": ".----",
"2": "..---",
"3": "...--",
"4": "....-",
"5": ".....",
"6": "-....",
"7": "--...",
"8": "---..",
"9": "----.",
"0": "-----",
'"': ".-..-.",
"$": "...-..-",
"'": ".----.",
"(": "-.--.",
")": "-.--.-",
"[": "-.--.",
"]": "-.--.-",
"+": ".-.-.",
",": "--..--",
"-": "-....-",
".": ".-.-.-",
"/": "-..-.",
":": "---...",
";": "-.-.-.",
"=": "-...-",
"?": "..--..",
"@": ".--.-.",
"_": "..--.-",
"!": "---.",
};
MorseNode.prototype.playChar = function(t, c) {
for(var i = 0; i < c.length; i++) {
switch(c[i]) {
case '.':
this._gain.gain.setValueAtTime(this._maxGain, t);
t += this._dot;
this._gain.gain.setValueAtTime(0.0, t);
break;
case '-':
this._gain.gain.setValueAtTime(this._maxGain, t);
t += 3 * this._dot;
this._gain.gain.setValueAtTime(0.0, t);
break;
}
t += this._dot;
}
return t;
}
MorseNode.prototype.playString = function(t, w) {
w = w.toUpperCase();
var startT = t;
var now = new Date();
for(var i = 0; i < w.length; i++) {
var charAt = 0;
this._intervals.push(setTimeout(function() { setCaret(charAt); charAt++ }, (t-startT-2*this._space)*1000.0));
if(w[i] == ' ') {
t += 3 * this._dot; // 3 dots from before, three here, and
// 1 from the ending letter before.
}
else if(this.MORSE[w[i]] != undefined) {
t = this.playChar(t, this.MORSE[w[i]]);
t += 2 * this._space;
}
}
return t;
}