JSFiddle - React, Tailwind, and code Playground
HTML
<textarea id="text" placeholder="Plaintext in">/pr FTW</textarea>
<textarea id="code" placeholder="Morse out"></textarea>
<br/>
<button id="play">Play!</button>
CSS
textarea {
position: absolute;
width: 45%;
height: 70px;
margin: 20px;
}
#text {
left: 0;
}
#code {
right: 0;
}
#play {
position: absolute;
top: 100px;
right: 20px;
}
JavaScript
var playNote = (function () {
var ctx = new(window.AudioContext || window.webkitAudioContext);
var tones = {
beep: function (duration, callback) {
var osc = ctx.createOscillator();
osc.connect(ctx.destination);
osc.type = 1;
osc.noteOn(0);
window.setTimeout(function () {
osc.noteOff(0);
callback();
}, duration);
},
silence: function (duration, callback) {
window.setTimeout(callback, duration);
}
};
var notes = {
'-': {
tone: 'beep',
duration: 600
},
'.': {
tone: 'beep',
duration: 200
},
' ': {
tone: 'silence',
duration: 200
}
};
var pause = 50;
return function (note, callback) {
note = notes[note];
tones[note.tone](note.duration, function () {
tones.silence(pause, callback);
});
};
}());
var playMorse = function playMorse(code) {
if (code.length) {
playNote(code[0], playMorse.bind(null, code.slice(1)));
}
};
var 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: '--..',
0: '-----',
1: '.----',
2: '..---',
3: '...--',
4: '....-',
5: '.....',
6: '-....',
7: '--...',
8: '---..',
9: '----.',
'.': '.-.-.-',
',': '--..--',
':': '---...',
'?': '..--..',
'\'': '.----.',
'-': '-....-',
'/': '-..-.',
'@': '.--.-.',
'=': '-...-',
};
var inverseMorse = Object.keys(morse).reduce(function (acc, key) {
acc[morse[key]] = key;
return...