Skip to content

Instantly share code, notes, and snippets.

@myme
Last active December 29, 2020 19:15
Show Gist options
  • Save myme/7554709 to your computer and use it in GitHub Desktop.
Save myme/7554709 to your computer and use it in GitHub Desktop.
Testing out Web Audio API with a simple morse code generator.
(function () {
"use strict";
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var morseAlphabet = {
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: '-----'
};
var unit = 100;
window.generateMorse = function (input) {
var destination = audioCtx.destination;
var letters = input.trim().replace(/\s+/, ' ').split('');
var letter;
var oscillator = audioCtx.createOscillator();
var offset = 0;
var morse;
oscillator.type = 'triangle';
oscillator.start(0);
var connect = function () {
oscillator.connect(destination);
};
var disconnect = function () {
oscillator.disconnect(0);
};
while (letters.length) {
letter = letters.shift();
morse = morseAlphabet[letter].split('');
while (morse.length) {
setTimeout(connect, offset);
offset += morse.shift() === '.' ? unit : unit * 3;
setTimeout(disconnect, offset);
if (morse.length) {
offset += unit;
}
}
if (letters.length) {
if (letters[0] === ' ') {
offset += unit * 7;
letters.shift();
} else {
offset += unit * 3;
}
}
}
setTimeout(function () {
oscillator.disconnect(audioCtx.destination);
oscillator.stop(0);
}, offset);
};
}());
<!DOCTYPE html>
<body>
<script src="audio.js"></script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment