Created by CoderDojo Dublin / @coderdojodublin
<html> <head> <script type="type/javascript"> function playMessage() { alert(document.forms['morse'].message.value); } </script> </head> <body> <form name="morse"> <input name="message" type="text" /> <a href="javascript:playMessage()">Play</a> </form> </body> <html>
var LOOKUP_TABLE = { "O": "---", "S": "..." }; function translateCharacter(ch) { var translated = LOOKUP_TABLE[ch.toUpperCase()]; return translated != undefined ? translated : ''; } function playMessage() { var message = document.forms['morse'].message.value; var morse = ''; for (var i = 0; i < message.length; i++) morse += message[i] == ' ' ? ' ' : translateCharacter(message[i]); alert(morse); }
-... . -.-. --- --- .-..
function MorsePlayer(ac, rate) { this._oscillator = ac.createOscillator(); this._oscillator.frequency.value = 750; this._oscillator.connect(ac.destination); this._oscillator.start(0); } var ac = new (window.AudioContext || window.webkitAudioContext)(); var player = new MorsePlayer(ac);
function MorsePlayer(ac, rate) { this._oscillator = ac.createOscillator(); this._gain = ac.createGain(); this._gain.gain.value = 0; this._oscillator.frequency.value = 750; this._oscillator.connect(this._gain); if(rate == undefined) { rate = 20; } this._dot = 1.2 / rate; this._oscillator.start(0); } MorsePlayer.prototype.connect = function(target) { return this._gain.connect(target); } var ac = new (window.AudioContext || window.webkitAudioContext)(); var player = new MorsePlayer(ac); player.connect(ac.destination);
MorsePlayer.prototype.playCode = function(time, code) { for(var i = 0; i < code.length; i++) { this._gain.gain.setValueAtTime(1.0, time); switch(code[i]) { case '.': time += this._dot; break; case '-': time += 3 * this._dot; break; } this._gain.gain.setValueAtTime(0.0, time); time += this._dot; } return time; }
Play S
function playMessage() { player.playMessage(ac.currentTime, document.forms['morse'].message.value); return false; }
MorsePlayer.prototype.playMessage = function(time, message) { for (var i = 0; i < message.length; i++) { if (message[i] == ' ') { time += 3 * this._dot; } else { var code = translateCharacter(message[i]); time = player.playCode(time, code); time += 2 * this._dot; } } }