Morse Code Meets Web Audio: Building a Beep Generator in JavaScript

摩斯电码遇上 Web Audio:用 JavaScript 制作蜂鸣发生器
https://ift.tt/oUEW5sr
摩斯电码已有近两个世纪的历史,却意外地成为学习 Web Audio API 的绝佳练习项目。把点和划转换成实际声音,整个项目小巧而简单:只需一个振荡器、一个增益节点和一个简单的计时循环。
计时基础
摩斯电码的时长以时间单位计算。点持续一个单位,划持续三个单位;同一个字母内符号之间的间隔为一个单位,字母之间的间隔为三个单位,单词之间的间隔为七个单位。如果一个单位是 80 毫秒,那么划就是 240 毫秒,单词间隔则是 560 毫秒。其余工作不过是安排播放时间。
生成蜂鸣声
使用 Web Audio API,无需任何音频文件就能生成清晰的音调。创建一个 AudioContext,将振荡器连接到增益节点,然后通过启动和停止振荡器来生成每个点和划:
const ctx = new AudioContext();
const MORSE = { A: ".-", B: "-...", S: "...", O: "---" };
function beep(durationMs, when) {
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.type = "sine";
osc.frequency.value = 700; // 柔和悦耳的 700 Hz 音调
osc.connect(gain).connect(ctx.destination);
gain.gain.setValueAtTime(0.0001, when);
gain.gain.exponentialRampToValueAtTime(0.5, when + 0.01);
gain.gain.setValueAtTime(0.5, when + durationMs / 1000 - 0.01);
gain.gain.exponentialRampToValueAtTime(0.0001, when + durationMs / 1000);
osc.start(when);
osc.stop(when + durationMs / 1000);
}
function playMorse(text) {
const unit = 0.08; // 每个单位 80 毫秒
let t = ctx.currentTime + 0.1;
for (const ch of text.toUpperCase()) {
if (ch === " ") { t += unit * 7; continue; }
const code = MORSE[ch];
if (!code) continue;
for (const sym of code) {
const len = sym === "." ? unit : unit * 3;
beep(len * 1000, t);
t += len + unit;
}
t += unit * 2; // 字母间隔(上面已加过 1 个单位)
}
}
playMorse("SOS");
增益包络很重要:突然启动和停止振荡器会产生可听见的咔嗒声,因此在几毫秒内逐渐调高、调低增益,可以让蜂鸣声更加平滑。
在线试用
如果你想听摩斯电码,却不想自己编写代码,可以试试 Morse Zone。这是一个免费的在线摩斯电码转换器,可以将文本转换为摩斯电码,并直接在浏览器中播放音频,方便你核对自己制作的蜂鸣发生器是否生成了正确的信号。无需注册。
接下来可以做什么
基础蜂鸣器运行正常后,还可以尝试添加通过麦克风收听的解码器、以每分钟字数为单位调节速度,以及与音频同步的可视信号灯。古老的通信协议配上现代 API,是个很适合周末动手的项目。
HI-FI News
来源:DEV Community:javascript https://ift.tt/dWL3let
2026年10月22日 上午06:39
October 22, 2026 at 06:39AM
-
Product on sale
Audiophile Vinyl Records Cleaning BundleOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Product on sale
Easy Start Vinyl Records Cleaning KitOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Vinyl Records Cleaner Easy Groove Concentrate€34.95 incl. VAT -
Easy Groove Super Set€199.00 incl. VAT -
Easy Groove Enzycaster – vinyl records prewash cleaner€34.95 incl. VAT -
Easy Groove Extreme MK. II- vinyl records prewash cleaner€45.00 incl. VAT -
Vinyl Records Cleaner – Easy Groove Virgin Concentrate€35.00 incl. VAT -
Easy Groove Spray&Wipe vinyl records cleaner€34.95 incl. VAT








