RosettaCodeData/Task/Morse-code/Pluto/morse-code.pluto
2026-04-30 12:34:36 -04:00

60 lines
2.2 KiB
Text

local audio = require "audio"
local char_to_morse = {
["!"] = "---.", ['"'] = ".-..-.", ["$"] = "...-..-", ["'"] = ".----.",
["("] = "-.--.", [")"] = "-.--.-", ["+"] = ".-.-.", [","] = "--..--",
["-"] = "-....-", ["."] = ".-.-.-", ["/"] = "-..-.",
["0"] = "-----", ["1"] = ".----", ["2"] = "..---", ["3"] = "...--",
["4"] = "....-", ["5"] = ".....", ["6"] = "-....", ["7"] = "--...",
["8"] = "---..", ["9"] = "----.",
[":"] = "---...", [";"] = "-.-.-.", ["="] = "-...-", ["?"] = "..--..",
["@"] = ".--.-.",
["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"] = "--..",
["["] = "-.--.", ["]"] = "-.--.-", ["_"] = "..--.-"
}
local function text_to_morse(text)
text = text:upper()
local morse = ""
for i = 1, #text do
local c = text[i]
if c == " " then
morse ..= string.rep(" ", 7)
else
local m = char_to_morse[c]
if m then morse ..= m:split(""):concat(" ") .. " " end
end
end
return morse:rstrip()
end
local morse = text_to_morse("Hello world!")
print(morse) -- print to terminal
-- Now create a .wav file.
morse = morse:replace("-", "...") -- replace 'dash' with 3 'dot's
local data = {}
local sample_rate = 44100
local samples = 0.2 * sample_rate -- number of samples assuming 'dot' takes 200 ms
local freq = 500 -- say
local omega = 2 * math.pi * freq
for i = 1, #morse do
local c = morse[i]
if c == "." then
for s = 0, samples -1 do
local value = math.round(32 * math.sin(omega * s / sample_rate)) & 255
data:insert(value)
end
else
for _ = 1, samples do data:insert(0) end
end
end
local filepath = "morse_code.wav"
audio.create(filepath, data, sample_rate)
audio.play(filepath)