Morse code: Difference between revisions
Content deleted Content added
Scala added. |
Add ed example |
||
(43 intermediate revisions by 25 users not shown) | |||
Line 1:
{{task|Sound}}
{{requires|Sound}}
[[Category:Temporal media]]
{{omit from|ML/I}}
[[wp:Morse_code|Morse code]] is one of the simplest and most versatile methods of telecommunication in existence.
It has been in use for more than
Line 14 ⟶ 16:
or indicate them somehow (e.g. with a different pitch).
<br><br>
=={{header|8086 Assembly}}==
This program runs under MS-DOS and outputs to the PC speaker. It reads the text
from standard input until EOF is reached.
<syntaxhighlight lang="asm"> cpu 8086
bits 16
;;; I/O ports
KBB: equ 61h ; Keyboard controller port B (also controls speaker)
PITC2: equ 42h ; Programmable Interrupt Timer, channel 2 (frequency)
PITCTL: equ 43h ; PIT control port.
;;; Control bits
SPKR: equ 3 ; Lower two bits of KBB determine speaker on/off
CTR: equ 6 ; Counter select offset in PIT control byte
CBITS: equ 4 ; Size select offset in PIT control byte
B16: equ 3 ; 16-bit mode for the PIT counter
MODE: equ 1 ; Offset of mode in PIT control byte
SQWV: equ 3 ; Square wave mode
;;; Software interrupts
CLOCK: equ 1Ah ; BIOS clock function interrupt
DOS: equ 21h ; MS-DOS syscall interrupt
;;; MS-DOS syscalls
read: equ 3Fh ; Read from file
section .text
org 100h
;;; Set up the PIT to generate a 'C' note
cli
mov al,(2<<CTR)|(B16<<CBITS)|(SQWV<<MODE)
out PITCTL,al
mov ax,2280 ; Divisor of main oscillator frequency
out PITC2,al ; Output low byte first,
xchg al,ah
out PITC2,al ; Then high byte.
sti
;;; Read from stdin and sound as morse
input: mov ah,read ; Read
xor bx,bx ; from STDIN
mov cx,buf.size ; into the buffer
mov dx,buf
int DOS
jc stop ; Carry set = error, stop
test ax,ax ; Did we get any characters?
jnz go ; If not, we're done, so stop
stop: ret
go: mov cx,ax ; Loop counter = how many characters we have
mov si,buf ; Start at buffer size
dochar: lodsb ; Get current character
cmp al,26 ; End of file?
je stop ; Then stop
push cx ; Save pointer and counter
push si
call char ; Sound out this character
pop si ; Restore pointer and counter
pop cx
loop dochar ; If more characters, do the next one
jmp input ; Afterwards, try to get more input
;;; Sound ASCII character in AL
char: and al,127 ; 7-bit ASCII
sub al,32 ; Word separator? (<=32)
ja .snd ; If not, look up in table
mov bx,4 ; Otherwise, 'sound' a word space
jmp delay ; (4 more ticks to form 7-tick delay)
.snd: mov bx,morse ; Find offset in morse pulse table
xlatb
test al,al ; If it is zero, we want to ignore it
jz .out
xor ah,ah ; Otherwise, find its address
mov bx,ax
lea si,[bx+morse.P] ; and store it in SI.
xor bh,bh ; BX = BL in the following code
.byte: lodsb ; Get pulse byte
mov cx,4 ; Four pulses per byte
.pulse: mov bl,3 ; Load low pulse in BL
and bl,al
test bl,bl ; If it is zero,
jz .out ; We're done
mov bp,ax ; Otherwise, keep AX
call pulse ; Sound the pulse
mov ax,bp ; Restore AX
shr al,1 ; Next pulse
shr al,1
loop .pulse
jmp .byte ; If no zero pulse seen yet, next byte
.out: mov bl,2 ; 2 ticks more delay to form inter-char space
jmp delay
;;; Sound morse code pulse w/delay
pulse: cli ; Turn off interrupts
in al,KBB ; Read current configuration
or al,SPKR ; Turn speaker on
out KBB,al ; Write configuration back
sti ; Turn interrupts back on
call delay ; Delay for BX ticks
cli ; Turn off interrupts
in al,KBB ; Read current configuration
and al,~SPKR ; Turn speaker off
out KBB,al ; Write configuration back
sti ; Turn interrupts back on
mov bx,1 ; Intra-character delay = 1 tick
;;; Delay for BX ticks
delay: push bx ; Keep the registers we alter
push cx
push dx
xor ah,ah ; Clock function 0 = get ticks
int CLOCK ; Get current ticks (in CX:DX)
add bx,dx ; BX = time for which to wait
.wait: int CLOCK ; Wait for that time to occur
cmp dx,bx ; Are we there yet?
jbe .wait ; If not, try again
pop dx ; Restore the registers
pop cx
pop bx
ret
section .data
morse: ;;; Printable ASCII to pulse mapping (32-122)
db .n_-.P, .excl-.P, .dquot-.P, .n_-.P ; !"#
db .dolar-.P, .n_-.P, .amp-.P, .quot-.P;$%&'
db .open-.P, .close-.P, .n_-.P, .plus-.P;()*+
db .comma-.P, .minus-.P, .dot-.P, .slsh-.P;,-./
db .n0-.P, .n1-.P, .n2-.P, .n3-.P ;0123
db .n4-.P, .n5-.P, .n6-.P, .n7-.P ;4567
db .n8-.P, .n9-.P, .colon-.P, .semi-.P;89:;
db .n_-.P, .eq-.P, .n_-.P, .qm-.P ;<=>?
db .at-.P, .a-.P, .b-.P, .c-.P ;@ABC
db .d-.P, .e-.P, .f-.P, .g-.P ;DEFG
db .h-.P, .i-.P, .j-.P, .k-.P ;HIJK
db .l-.P, .m-.P, .n-.P, .o-.P ;LMNO
db .p-.P, .q-.P, .r-.P, .s-.P ;PQRS
db .t-.P, .u-.P, .v-.P, .w-.P ;TUVW
db .x-.P, .y-.P, .z-.P, .n_-.P ;XYZ[
db .n_-.P, .n_-.P, .n_-.P, .uscr-.P;\]^_
db .n_-.P, .a-.P, .b-.P, .c-.P ;`abc
db .d-.P, .e-.P, .f-.P, .g-.P ;defg
db .h-.P, .i-.P, .j-.P, .k-.P ;hijk
db .l-.P, .m-.P, .n-.P, .o-.P ;lmno
db .p-.P, .q-.P, .r-.P, .s-.P ;pqrs
db .t-.P, .u-.P, .v-.P, .w-.P ;tuvw
db .x-.P, .y-.P, .z-.P, .n_-.P ;xyz{
db .n_-.P, .n_-.P, .n_-.P, .n_-.P ;|}~
.P: ;;; Morse pulses are stored four to a byte, lowest bits first
.n_: db 0 ; To ignore undefined characters
.a: db 0Dh
.b: db 57h,0
.c: db 77h,0
.d: db 17h
.e: db 1h
.f: db 75h,0
.g: db 1Fh
.h: db 55h,0
.i: db 5h
.j: db 0FDh,0
.k: db 37h
.l: db 5Dh,0
.m: db 0Fh
.n: db 7h
.o: db 3Fh
.p: db 7Dh,0
.q: db 0DFh,0
.r: db 1Dh
.s: db 15h
.t: db 3h
.u: db 35h
.v: db 0D5h,0
.w: db 3Dh
.x: db 0D7h,0
.y: db 0F7h,0
.z: db 5Fh,0
.n0: db 0FFh,3
.n1: db 0FDh,3
.n2: db 0F5h,3
.n3: db 0D5h,3
.n4: db 55h,3
.n5: db 55h,1
.n6: db 57h,1
.n7: db 5Fh,1
.n8: db 7Fh,1
.n9: db 0FFh,1
.dot: db 0DDh,0Dh
.comma: db 5Fh,0Fh
.qm: db 0F5h,5
.quot: db 0FDh,7
.excl: db 77h,0Fh
.slsh: db 0D7h,1
.open: db 0F7h,1
.close: db 0F7h,0Dh
.amp: db 5Dh,1
.colon: db 7Fh,5
.semi: db 77h,7
.eq: db 57h,3
.plus: db 0DDh,1
.minus: db 57h,0Dh
.uscr: db 0F5h,0Dh
.dquot: db 5Dh,7
.dolar: db 0D5h,35h
.at: db 7Dh,7
section .bss
buf: resb 1024 ; 1K buffer
.size: equ $-buf</syntaxhighlight>
=={{header|ABAP}}==
<
TYPES: BEGIN OF y_morse_code,
letter TYPE string,
Line 87 ⟶ 287:
ELSE LET prev = index - 1 IN to_upper( word+prev(1) ) ) ]-code OPTIONAL )
IN NEXT word_coded = |{ word_coded } { _morse_code }| ) ) ) )
)->display( ).</
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE PTR="CARD"
DEFINE COUNT="$60"
PTR ARRAY code(COUNT)
BYTE
PALNTSC=$D014,
dotDuration,dashDuration,
intraGapDuration,letterGapDuration,wordGapDuration
PROC Init()
Zero(code,COUNT)
code('!)="-.-.--" code('")=".-..-."
code('$)="...-..-" code('&)=".-..."
code('')=".----." code('()="-.--.-"
code('))="---.." code('+)=".-.-."
code(',)="--..--" code('-)="-....-"
code('.)=".-.-.-" code('/)="-..-."
code('0)="-----" code('1)=".----"
code('2)="..---" code('3)="...--"
code('4)="....-" code('5)="....."
code('6)="-...." code('7)="--..."
code('8)="---.." code('9)="----."
code(':)="---..." code(';)="-.-.-."
code('=)="-...-" code('?)="..--.."
code('@)=".--.-." code('A)=".-"
code('B)="-..." code('C)="-.-."
code('D)="-.." code('E)="."
code('F)="..-." code('G)="--."
code('H)="...." code('I)=".."
code('J)=".---" code('K)="-.-"
code('L)=".-.." code('M)="--"
code('N)="-." code('O)="---"
code('P)=".--." code('Q)="--.-"
code('R)=".-." code('S)="..."
code('T)="-" code('U)="..-"
code('V)="...-" code('W)=".--"
code('X)="-..-" code('Y)="-.--"
code('Z)="--.." code('\)=".-..-."
code('_)="..--.-"
IF PALNTSC=15 THEN
dotDuration=6
ELSE
dotDuration=5
FI
dashDuration=2*dotDuration
intraGapDuration=dotDuration
letterGapDuration=3*intraGapDuration
wordGapDuration=7*intraGapDuration
RETURN
PROC Wait(BYTE frames)
BYTE RTCLOK=$14
frames==+RTCLOK
WHILE frames#RTCLOK DO OD
RETURN
PROC ProcessSound(CHAR ARRAY s BYTE last)
BYTE i
FOR i=1 TO s(0)
DO
Sound(0,30,10,10)
IF s(i)='. THEN
Wait(dotDuration)
ELSE
Wait(dashDuration)
FI
Sound(0,0,0,0)
IF i<s(0) THEN
Wait(intraGapDuration)
FI
OD
RETURN
PROC Process(CHAR ARRAY a)
CHAR ARRAY seq,subs
BYTE i,first,afterSpace
CHAR c
PrintE(a)
first=1
afterSpace=0
FOR i=1 TO a(0)
DO
c=a(i)
IF c>='a AND c<='z THEN
c=c-'a+'A
ELSEIF c>=COUNT THEN
c=0
FI
seq=code(c)
IF seq#0 THEN
IF first=1 THEN
first=0
ELSE
Put(' )
IF afterSpace=0 THEN
Wait(letterGapDuration)
FI
FI
subs=code(c)
Print(subs)
ProcessSound(subs)
afterSpace=0
ELSEIF c=' THEN
Print(" ")
Wait(wordGapDuration)
afterSpace=1
ELSE
afterSpace=0
FI
OD
PutE() PutE()
Wait(wordGapDuration)
RETURN
PROC Main()
Init()
Process("SOS")
Process("Atari Action!")
Process("www.rosettacode.org")
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Morse_code.png Screenshot from Atari 8-bit computer]
<pre>
SOS
... --- ...
Atari Action!
.- - .- .-. .. .- -.-. - .. --- -. -.-.--
www.rosettacode.org
.-- .-- .-- .-.-.- .-. --- ... . - - .- -.-. --- -.. . .-.-.- --- .-. --.
</pre>
=={{header|Ada}}==
Line 94 ⟶ 432:
Specification of the package :
<
type Symbols is (Nul, '-', '.', ' ');
Line 133 ⟶ 471:
others => (1, " ")); -- Dummy => Other characters do not need code.
end Morse;</
<
use Ada, Ada.Strings, Ada.Strings.Maps, Interfaces;
Line 205 ⟶ 543:
Dit_ms := C.unsigned (Integer (Dit * 1000));
Dah_ms := C.unsigned (Integer (Dah * 1000));
end Morse;</
Main program :
<
procedure Morse_Tx is
begin
Morsebeep (Convert ("Science sans Conscience"));
end Morse_Tx;</
=={{header|AppleScript}}==
This caters for non-diacritical English letters, numerals, and the punctuation found on the Wikipedia page and makes a burping noise for anything else. The morse sounds brisker and smoother if the script's run as an application or from Script Menu rather than in Script Editor or Script Debugger.
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"
use framework "AppKit"
on morseCode(msg)
script morse
-- Unit duration in seconds and sounds used.
property units : 0.075
property morseSound : current application's class "NSSound"'s soundNamed:("Glass")
property unknownCharacterSound : current application's class "NSSound"'s soundNamed:("Frog")
-- Unicode IDs of in-range but uncatered-for punctuation characters.
property unrecognisedPunctuation : {35, 37, 42, 60, 62, 91, 92, 93, 94}
-- Dits and dahs for recognised characters, in units.
property letters : {{1, 3}, {3, 1, 1, 1}, {3, 1, 3, 1}, {3, 1, 1}, {1}, {1, 1, 3, 1}, {3, 3, 1}, {1, 1, 1, 1}, {1, 1}, ¬
{1, 3, 3, 3}, {3, 1, 3}, {1, 3, 1, 1}, {3, 3}, {3, 1}, {3, 3, 3}, {1, 3, 3, 1}, {3, 3, 1, 3}, {1, 3, 1}, {1, 1, 1}, ¬
{3}, {1, 1, 3}, {1, 1, 1, 3}, {1, 3, 3}, {3, 1, 1, 3}, {3, 1, 3, 3}, {3, 3, 1, 1}}
property underscore : {1, 1, 3, 3, 1, 3}
property digitsAndPunctuation : {{3, 3, 3, 3, 3}, {1, 3, 3, 3, 3}, {1, 1, 3, 3, 3}, {1, 1, 1, 3, 3}, ¬
{1, 1, 1, 1, 3}, {1, 1, 1, 1, 1}, {3, 1, 1, 1, 1}, {3, 3, 1, 1, 1}, {3, 3, 3, 1, 1}, {3, 3, 3, 3, 1}, ¬
{3, 3, 3, 1, 1, 1}, {3, 1, 3, 1, 3, 1}, missing value, {3, 1, 1, 1, 3}, missing value, ¬
{1, 1, 3, 3, 1, 1}, {1, 3, 3, 1, 3, 1}}
property |punctuation| : {{3, 1, 3, 1, 3, 3}, {1, 3, 1, 1, 3, 1}, missing value, {1, 1, 1, 3, 1, 1, 3}, missing value, ¬
{1, 3, 1, 1, 1}, {1, 3, 3, 3, 3, 1}, {3, 1, 3, 3, 1}, {3, 1, 3, 3, 1, 3}, missing value, ¬
{1, 3, 1, 3, 1}, {3, 3, 1, 1, 3, 3}, {3, 1, 1, 1, 1, 3}, {1, 3, 1, 3, 1, 3}, {3, 1, 1, 3, 1}}
-- Unicode IDs of the message's characters.
property UnicodeIDs : (id of msg) as list
on sendCharacter(ditsAndDahs)
repeat with ditOrDah in ditsAndDahs
tell morseSound to play()
delay (ditOrDah * units)
tell morseSound to stop()
delay (1 * units)
end repeat
delay (2 * units) -- Previous 1 unit + 2 units = 3 units between characters.
end sendCharacter
on sendMessage()
-- Play an extremely short sound to ensure the sound system's awake for the first morse beep.
tell morse to sendCharacter({0})
-- Output the message.
repeat with i from 1 to (count UnicodeIDs)
set thisID to item i of my UnicodeIDs
if ((thisID > 122) or (thisID < 32) or (thisID is in unrecognisedPunctuation)) then
-- Character not catered for. Play alternative sound.
tell unknownCharacterSound to play()
delay (3 * units)
tell unknownCharacterSound to stop()
delay (3 * units)
else if ((thisID > 64) and ((thisID < 91) or (thisID > 96))) then -- English letter.
sendCharacter(item (thisID mod 32) of my letters)
else if (thisID is 95) then -- Underscore.
sendCharacter(underscore)
else if (thisID > 47) then -- Digit, colon, semicolon, equals, or question mark.
sendCharacter(item (thisID - 47) of my digitsAndPunctuation)
else if (thisID > 32) then -- Other recognised punctuation.
sendCharacter(item (thisID - 32) of my |punctuation|)
else -- Space.
delay (4 * units) -- Previous 3 units + 4 units = 7 units between "words".
end if
end repeat
end sendMessage
end script
tell morse to sendMessage()
end morseCode
-- Test code:
morseCode("Coded in AppleScrip†.")</syntaxhighlight>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">; set the morse code
code: #[
; letters
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: "--.."
; digits
"0": "-----"
"1": ".----"
"2": "..---"
"3": "...--"
"4": "....-"
"5": "....."
"6": "-...."
"7": "--..."
"8": "---.."
"9": "----."
]
; print an encoded message
str: "hello world 2019"
out: ""
loop split str 'ch [
if not? whitespace? ch -> 'out ++ code\[ch]
'out ++ " "
]
print out</syntaxhighlight>
{{out}}
<pre>.... . .-.. .-.. --- .-- --- .-. .-.. -.. ..--- ----- .---- ----.</pre>
=={{header|AutoHotkey}}==
This function converts acceptable characters into dot-dash notation then uses SoundBeep to play them.
The frequency and element length are stored near the bottom of the script.
It uses the short form of if else that is implemented, to not have such a long script
<syntaxhighlight lang="autohotkey">TestString := "Hello World! abcdefg @\;"
MorseBeep(teststring)
return
MorseBeep(passedString)
{
StringLower, passedString, passedString
Loop, Parse, passedString ;This loop stores each character in A_loopField one by one using the more compact form of "if else", by var := x>y ? val1 : val2 which stores val1 in var if x > y, otherwise it stores val2, this can be used together to make a single line of if else
morse .= A_LoopField = " " ? " " : A_LoopField = "a" ? ".- " : A_LoopField = "b" ? "-... " : A_LoopField = "c" ? "-.-. " : A_LoopField = "d" ? "-.. " : A_LoopField = "e" ? ". " : A_LoopField = "f" ? "..-. " : A_LoopField = "g" ? "--. " : A_LoopField = "h" ? ".... " : A_LoopField = "i" ? ".. " : A_LoopField = "j" ? ".--- " : A_LoopField = "k" ? "-.- " : A_LoopField = "l" ? ".-.. " : A_LoopField = "m" ? "-- " : A_LoopField = "n" ? "-. " : A_LoopField = "o" ? "--- " : A_LoopField = "p" ? ".--. " : A_LoopField = "q" ? "--.- " : A_LoopField = "r" ? ".-. " : A_LoopField = "s" ? "... " : A_LoopField = "t" ? "- " : A_LoopField = "u" ? "..- " : A_LoopField = "v" ? "...- " : A_LoopField = "w" ? ".-- " : A_LoopField = "x" ? "-..- " : A_LoopField = "y" ? "-.-- " : A_LoopField = "z" ? "--.. " : A_LoopField = "!" ? "---. " : A_LoopField = "\" ? ".-..-. " : A_LoopField = "$" ? "...-..- " : A_LoopField = "'" ? ".----. " : A_LoopField = "(" ? "-.--. " : A_LoopField = ")" ? "-.--.- " : A_LoopField = "+" ? ".-.-. " : A_LoopField = "," ? "--..-- " : A_LoopField = "-" ? "-....- " : A_LoopField = "." ? ".-.-.- " : A_LoopField = "/" ? "-..-. " : A_LoopField = "0" ? "----- " : A_LoopField = "1" ? ".---- " : A_LoopField = "2" ? "..--- " : A_LoopField = "3" ? "...-- " : A_LoopField = "4" ? "....- " : A_LoopField = "5" ? "..... " : A_LoopField = "6" ? "-.... " : A_LoopField = "7" ? "--... " : A_LoopField = "8" ? "---.. " : A_LoopField = "9" ? "----. " : A_LoopField = ":" ? "---... " : A_LoopField = ";" ? "-.-.-. " : A_LoopField = "=" ? "-...- " : A_LoopField = "?" ? "..--.. " : A_LoopField = "@" ? ".--.-. " : A_LoopField = "[" ? "-.--. " : A_LoopField = "]" ? "-.--.- " : A_LoopField = "_" ? "..--.- " : "ERROR" ; ---End conversion loop---
Loop, Parse, morse
{
morsebeep := 120
if (A_LoopField = ".")
SoundBeep,
If (A_LoopField = "-")
SoundBeep,
If (A_LoopField = " ")
Sleep,
}
return morse ;Returns the text in morse code
} ; ---End Function Morse---</syntaxhighlight>
=={{header|AWK}}==
AWK cannot play sounds by itself,
so here we just translate text to dits and dots:
<
BEGIN { FS="";
m="A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.";
Line 382 ⟶ 716:
printf("\n");
}
</syntaxhighlight>
{{Out}} with input "sos sos titanic"
Line 389 ⟶ 723:
</pre>
=={{header|bash}}==
IMC bash implementation
{{works with|GNU bash, version 4 + sox (optional)}}
<syntaxhighlight lang="bash">
#!/bin/bash
# michaeltd 2019-11-29 https://github.com/michaeltd/dots/blob/master/dot.files/.bashrc.d/.var/morse.sh
# https://en.wikipedia.org/wiki/Morse_code
# International Morse Code
# 1. Length of dot is 1 unit
# 2. Length of dash is 3 units
# 3. The space between parts of the same letter is 1 unit
# 4. The space between letters is 3 units.
# 5. The space between words is 7 units.
################################################################################
alpha2morse() {
local -A alpha_assoc=( [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]='----.' )
if [[ "${#}" -lt "1" ]]; then
echo -ne "Usage: ${FUNCNAME[0]} arguments...\n \
${FUNCNAME[0]} is an IMC transmitter. \n \
It'll transmit your messages to International Morse Code.\n" >&2
return 1
fi
while [[ -n "${1}" ]]; do
for (( i = 0; i < ${#1}; i++ )); do
local letter="${1:${i}:1}"
for (( y = 0; y < ${#alpha_assoc[${letter^^}]}; y++ )); do
case "${alpha_assoc[${letter^^}]:${y}:1}" in
".") echo -n "dot "; play -q -n -c2 synth .1 2> /dev/null || sleep .1 ;;
"-") echo -n "dash "; play -q -n -c2 synth .3 2> /dev/null || sleep .3 ;;
esac
sleep .1
done
echo
sleep .3
done
echo
sleep .7
shift
done
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
alpha2morse "${@}"
fi
</syntaxhighlight>
{{out}} (input: sos titanic sos):
<pre>
./morse.sh sos titanic sos
dot dot dot
dash dash dash
dot dot dot
dash
dot dot
dash
dot dash
dash dot
dot dot
dash dot dash dot
dot dot dot
dash dash dash
dot dot dot
</pre>
=={{header|BASIC}}==
Line 396 ⟶ 805:
Note that this will ''only'' work as-is under [[DOS]] (and [[Windows]] 9x); under NT systems, the <code>player</code> routine must be changed to use the <code>Beep</code> API call. ([http://www.freebasic.net/forum/viewtopic.php?p=20441#20441 This forum post] details how to use the speaker under Linux, DOS, and Windows in FreeBASIC; the Linux & DOS code differs further from the below by require inline assembly.)
<
'this determines the length of the notes
Line 455 ⟶ 864:
PLAY "p" + LTRIM$(STR$(noteLen))
NEXT i%
END SUB</
{{out}} (2 runs):
Line 467 ⟶ 876:
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<
DIM morse$(63)
FOR char% = 0 TO 63 : READ morse$(char%) : NEXT char%
Line 492 ⟶ 901:
DATA 33333,13333,11333,11133,11113,11111,31111,33111,33311,33331,333111,313131,6,31113,6,113311
DATA 133131,13,3111,3131,311,1,1131,331,1111,11,1333,313,1311,33,31,333
DATA 1331,3313,131,111,3,113,1113,133,3113,3133,3311,6,6,6,6,113313</
==={{header|Chipmunk Basic}}===
{{trans|Yabasic}}
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">10 rem Morse code
20 dim c$(54)
30 for f = 1 to 54
40 read l$ : read m$
50 d$ = d$+l$ : c$(f) = m$
60 next f
100 line input "Message? ";t$
105 t$ = ucase$(t$)
110 for f = 1 to len(t$)
120 p = instr(d$,mid$(t$,f,1))
130 if p > 0 then print c$(p); else print "?";
140 next f
150 print
160 goto 100
1000 data "A","._","B","_...","C","_._.","D","_..","E",".","F",".._."
1010 data "G","__.","H","....","I","..","J",".___","K","_._","L","._.."
1020 data "M","__","N","_.","O","___","P",".__.","Q","__._","R","._."
1030 data "S","...","T","_","U",".._","V","..._","W",".__","X","_.._"
1040 data "Y","_.__","Z","__..","1",".____","2","..___","3","...__"
1050 data "4","...._","5",".....","6","_....","7","__...","8","___.."
1060 data "9","____.","0","_____",".","._._._",",","__..__","?","..__.."
1070 data "'",".____.","!","_._.__","/","_.._.","(","_.__.",")","_.__._"
1080 data "&","._...",":","___...",";","_._._.","=","_..._","+","._._.","-","_...._"
1090 data "_","..__._","\","._.._.","$","..._.._","@",".__._."</syntaxhighlight>
==={{header|IS-BASIC}}===
<
110 STRING TONE$(48 TO 90)*5,ST$*254
120 SET CHARACTER 46,0,0,0,0,24,24,0,0,0:SET CHARACTER 47,0,0,0,0,126,126,0,0,0
Line 522 ⟶ 959:
350 CLEAR FONT
360 DATA .////,..///,...//,..../,.....,/....,//...,///..,////.,/////,"","","","","","",""
370 DATA ./,/...,/./.,/..,.,../.,//.,....,..,.///,/./,./..,//,/.,///,.//.,//./,./.,...,/,../,.../,.//,/../,/.//,//..</
==={{header|Commodore BASIC}}===
{{works with|Commodore BASIC|7.0}}
<p>This takes advantage of the PLAY statement in Commodore BASIC 7.0 on the C-128. Since we're in BASIC 7, it also uses
some of its structured programming features, such as DO...LOOP and BEGIN...BEND.</p>
<syntaxhighlight lang="basic">100 DI$="IA" : REM DIT = EIGHTH NOTE
110 DA$="Q.A": REM DA = DOTTED QUARTER NOTE
120 IS$="IR" : REM SPACE BETWEEN SYMS=1xDOT
130 IC$="QR" : REM EXTRA BETWEEN CHARS=2xDOT(TOTAL 3)
140 IW$="HR" : REM SPACE BETWEEN WORDS=4xDOT(TOTAL 7)
150 DIM MC$(127): REM READ CODE TABLE
160 DO
170 : READ C$
180 : IF C$="" THEN EXIT
190 : C=ASC(C$)
200 : READ C$
210 : MC$(C) = C$
220 LOOP
230 PRINT "ENTER MESSAGE:"
240 OPEN1,0:INPUT#1,M$:CLOSE1
250 TEMPO 128
260 P$="T7": REM ENVELOPE = ORGAN
270 FOR I=1 TO LEN(M$)
280 : A=ASC(MID$(M$,I))
290 : IF A=32 THEN BEGIN
300 : P$=P$+IW$
310 : BEND:ELSE IF MC$(A)<>"" THEN BEGIN
320 : C$=MC$(A)
330 : FOR J=1 TO LEN(C$)
340 : S$=MID$(C$,J,1)
350 : IF S$="." THEN BEGIN
360 : P$=P$+DI$
370 : BEND:ELSE BEGIN
380 : P$=P$+DA$
390 : BEND
400 : P$=P$+IS$
410 : NEXT J
420 : P$=P$+IC$
430 : BEND
440 NEXT I
450 PLAY P$
460 END
470 REM MORSE CODE TABLE DATA
500 DATA A,".-", B,"-...", C,"-.-."
510 DATA D,"-..", E,".", F,"..-.",G,"--."
520 DATA H,"....", I,"..", J,".---"
530 DATA K,"-.-", L,".-..", M,"--",N,"-."
540 DATA O,"---", P,".--.", Q,"--.-"
550 DATA R,".-.", S,"...", T,"-",U,"..-"
560 DATA V,"...-", W,".--", X,"-..-"
570 DATA Y,"-.--", Z,"--.."
580 DATA 0,"-----",1,".----",2,"..---"
590 DATA 3,"...--",4,"....-",5,"....."
600 DATA 6,"-....",7,"--...",8,"---.."
610 DATA 9,"----."
620 DATA ".",".-.-.-", ",","--..--"
630 DATA "?","..--.."
640 DATA ""</syntaxhighlight>
=={{header|Befunge}}==
Since Befunge doesn't have a way to output sound, this implementation just generates a text representation of the morse. The string to convert is read from stdin.
<
^v('_')v!:-*57g+3/"!"\%"!":+1\-*<
^$$,*84_\#!:#:2#-%#15#\9#/*#2+#,<
Line 535 ⟶ 1,030:
'(&*&#$&&*'$&)'%'/'########6)##$%
1'-')&$$.''&2'&%$'%&0'#%%%#&,'''(
&*&#$&&*'$&)'%'/'################</
{{out}}
Line 545 ⟶ 1,040:
One could substitute another program for ubuntu beep command.
<syntaxhighlight lang="c">
/*
Line 624 ⟶ 1,119:
return 0;
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
namespace Morse
{
class Morse
{
static void Main(string[] args)
{
string word = "sos";
Dictionary<string, string> Codes = new Dictionary<string, string>
{
{"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", "----."}
};
foreach (char c in word.ToCharArray())
{
string rslt = Codes[c.ToString()].Trim();
foreach (char c2 in rslt.ToCharArray())
{
if (c2 == '.')
Console.Beep(1000, 250);
else
Console.Beep(1000, 750);
}
System.Threading.Thread.Sleep(50);
}
}
}
}
</syntaxhighlight>
=={{header|C++}}==
<syntaxhighlight lang="c++">
/*
Michal Sikorski
Line 696 ⟶ 1,233:
}
</syntaxhighlight>
=={{header|Clojure}}==
<
(defn play [sample-rate bs]
Line 793 ⟶ 1,290:
(apply concat ,)
byte-array
(play sample-rate ,)))</
=={{header|CoffeeScript}}==
<
constructor : (@unit=0.05, @freq=700) ->
Line 846 ⟶ 1,343:
morse = new Morse()
morse.send 'hello world 0123456789'</
=={{header|D}}==
<syntaxhighlight lang="d">
import std.conv;
import std.stdio;
Line 908 ⟶ 1,405:
}
}
</syntaxhighlight>
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
program Morse;
Line 985 ⟶ 1,482:
Dictionary.Free;
end;
end.</
=={{header|EasyLang}}==
<syntaxhighlight>
txt$ = "sos sos"
#
chars$ = "abcdefghijklmnopqrstuvwxyz "
code$[] = [ ".-" "-..." "-.-." "-.." "." "..-." "--." "...." ".." ".---" "-.-" ".-.." "--" "-." "---" ".--." "--.-" ".-." "..." "-" "..-" "...-" ".--" "-..-" "-.--" "--.." " " ]
#
proc morse ch$ . .
ind = strpos chars$ ch$
sleep 0.4
for c$ in strchars code$[ind]
sleep 0.
elif c$ = "-"
sleep 0.8
.
print ""
.
.
for ch$ in strchars txt$
morse ch$
.
</syntaxhighlight>
=={{header|EchoLisp}}==
<
(require 'json)
(require 'hash)
Line 1,057 ⟶ 1,543:
(else (writeln) (blink)))
(set! EMIT (rest EMIT))))
</syntaxhighlight>
{{out}}
<pre>
Line 1,068 ⟶ 1,554:
(at-every 300 'play-morse)
</pre>
=={{header|ed}}==
Translation of [[#Se
<syntaxhighlight lang="sed">
# by Artyom Bologov
H
g/[Aa]/s//.- /g
g/[Bb]/s//-... /g
g/[Cc]/s//-.-. /g
g/[Dd]/s//-.. /g
g/[Ee]/s//. /g
g/[Ff]/s//..-. /g
g/[Gg]/s//--. /g
g/[Hh]/s//.... /g
g/[Ii]/s//.. /g
g/[Jj]/s//.--- /g
g/[Kk]/s//-.- /g
g/[Ll]/s//.-.. /g
g/[Mm]/s//-- /g
g/[Nn]/s//-. /g
g/[Oo]/s//--- /g
g/[Pp]/s//.-- /g
g/[Qq]/s//--.- /g
g/[Rr]/s//.-. /g
g/[Ss]/s//... /g
g/[Tt]/s//- /g
g/[Uu]/s//..- /g
g/[Vv]/s//...- /g
g/[Ww]/s//.-- /g
g/[Xx]/s//-..- /g
g/[Yy]/s//-.-- /g
g/[Zz]/s//--.. /g
,p
Q
</syntaxhighlight>
{{out}}
<pre>$ ed -s morse.input < morse.ed
Newline appended
.... . .-.. .-.. --- .-- --- .-. .-.. -.. !</pre>
=={{header|Elixir}}==
<
@morse %{"!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.",
"(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--",
Line 1,094 ⟶ 1,623:
end
IO.puts Morse.code("Hello, World!")</
{{out}}
Line 1,100 ⟶ 1,629:
.... . .-.. .-.. --- --..-- .-- --- .-. .-.. -.. ---.
</pre>
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
open System
open System.Threading
let morse = Map.ofList
[('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', "____. ")]
let beep c =
match c with
| '.' ->
printf "."
Console.Beep(1200, 250)
| '_' ->
printf "_"
Console.Beep(1200, 1000)
| _ ->
printf " "
Thread.Sleep(125)
let trim (s: string) = s.Trim()
let toMorse c = Map.find c morse
let lower (s: string) = s.ToLower()
let sanitize = String.filter Char.IsLetterOrDigit
let send = sanitize >> lower >> String.collect toMorse >> trim >> String.iter beep
send "Rosetta Code"
</syntaxhighlight>
{{out}}
<pre>._. ___ ... . _ _ ._ _._. ___ _.. .</pre>
=={{header|Factor}}==
<
"Hello world!" play-as-morse</
=={{header|Forth}}==
Line 1,109 ⟶ 1,678:
The Morse code generator could have taken the form of a look-up array with bit patterns cross referencing dits and dahs, but we instead used the Forth dictionary, which is functionally like a big case statement. By making each letter an executable routine in Forth we get a very succinct way to code our Morse. Proper sounding morse code requires precise time delays between the dits, dahs, letters and words. The program uses the Forth word "ms" which delays for n milliseconds and gives us real time control. This morse code sounds right.
There is a lot accomplished in 75 lines of code for a "low level" language.
<syntaxhighlight lang="text">
HEX
\ PC speaker hardware control (requires GIVEIO or DOSBOX for windows operation)
Line 1,189 ⟶ 1,758:
: ? . . - - . . ;
: , - - . . - - ;
: /
: . . - . - . - ;
PREVIOUS DEFINITIONS \ go back to previous namespace
: TRANSMIT MORSE TRANSMIT PREVIOUS ;</
Test at the Forth console
Line 1,201 ⟶ 1,770:
=={{header|FreeBASIC}}==
<
' FB 1.05.0 Win64
Line 1,278 ⟶ 1,847:
DyLibFree(library)
End
</syntaxhighlight>
=={{header|FutureBasic}}==
When compiled with FB, this code produces a packaged, stand-alone 64-bit application that will run on either Intel or the newer M-series Macs. It translates a text string into Morse Code and plays back characters along with their respective sounds. The oscillator frequency and volume, along with letter and word spacing, can be adjusted with the definitions at the head of the file. While the code meets the Rosetta Code parameters, it's by no means exhaustive. For instance, it does not include translation of punctuation or prosigns, and the GUI is minimal. It's simply a proof of concept. It's been tested on Catalina (10.15.x) to Monterey (12.4.x) with Ventura still in beta at the time of this post. The free FB compiler is available on the
[http://www.brilorsoftware.com/fb/pages/home.html FutureBasic] home page.
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
include "Tlbx AVKit.incl"
#define VOLUME 0.2
#define HZ_FREQUENCY 440.0
_ditDelay = 100
_dahDelay = 200
_spcDelay = 300
void local fn PlayCodeDone( ref as AVAudioPlayerNodeRef, userData as ptr )
NSLog(@"%@\b",userData)
end fn
local fn PlayFrequency( frequency as float, amplitude as float, character as CFStringRef ) as AVAudioPlayerNodeRef
static AVAudioEngineRef audioEngine
audioEngine = fn AVAudioEngineInit
AVAudioPlayerNodeRef player = fn AVAudioPlayerNodeInit
AVAudioMixerNodeRef mixer = fn AVAudioEngineMainMixerNode( audioEngine )
float sampleRate = fn AVAudioFormatSampleRate( fn AVAudioNodeOutputFormatForBus( mixer, 0 ) )
AVAudioFrameCount frameBufferLength = fn floorf( sampleRate / frequency ) * 1
AVAudioPCMBufferRef buffer = fn AVAudioPCMBufferWithFormat( fn AVAudioNodeOutputFormatForBus( player, 0 ), frameBufferLength )
AVAudioPCMBufferSetFrameLength( buffer, frameBufferLength )
NSInteger channelCount = fn AVAudioFormatChannelCount( fn AVAudioNodeOutputFormatForBus( mixer, 0 ) )
AVAudioFrameCount frameLength = fn AVAudioPCMBufferFrameLength( buffer )
ptr p = (ptr)fn AVAudioPCMBufferFloatChannelData(buffer)
xref floatChannelData(100) as ^float
floatChannelData = p
long i, channelNumber
float theta, value
^float channelBuffer
for i = 0 to frameLength - 1
theta = frequency * i * 2.0 * M_PI / sampleRate
value = fn sinf(theta)
for channelNumber = 0 to channelCount - 1
channelBuffer = floatChannelData(channelNumber)
cln channelBuffer[i] = value * amplitude;
next
next
AVAudioEngineAttachNode( audioEngine, player )
AVAudioEngineConnect( audioEngine, player, mixer, fn AVAudioNodeOutputFormatForBus( player, 0 ) )
fn AVAudioEngineStart( audioEngine, NULL )
AVAudioPlayerNodePlay( player )
AVAudioPlayerNodeScheduleBufferAtTime( player, buffer, NULL, AVAudioPlayerNodeBufferLoops, @fn PlayCodeDone, (ptr)character )
end fn = player
void local fn PlayMorseCode( play as BOOL, character as CFStringRef )
static AVAudioPlayerNodeRef player
select ( play )
case YES : player = fn PlayFrequency( HZ_FREQUENCY, VOLUME, character )
case NO : AVAudioPlayerNodeStop( player ) // : AppRemoveAllProperties
end select
end fn
local fn ParseCodeAndPlay( character as CFStringRef )
dispatchmain
if fn StringIsEqual( character, @"." ) then timerbegin : fn PlayMorseCode( YES, character ) : delay _ditDelay : fn PlayMorseCode( NO, NULL ) : timerend
if fn StringIsEqual( character, @"-" ) then timerbegin : fn PlayMorseCode( YES, character ) : delay _dahDelay : fn PlayMorseCode( NO, NULL ) : timerend
if fn StringIsEqual( character, @" " ) then timerbegin : NSLog(@" \b") : delay _spcDelay : timerend
if fn StringIsEqual( character, @"\n" ) then timerbegin : NSLog(@"") : timerend
dispatchend
end fn
local fn MorseCharacter( letter as CFStringRef ) as CFStringRef
CFDictionaryRef morseDict = @{
@"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":@"----."}
end fn = morseDict[letter]
local fn BuildMorseString( asciiStr as CFStringRef ) as CFStringRef
NSInteger i
CFStringRef processStr = fn StringLowerCaseString( asciiStr )
CFMutableStringRef mutStr = fn MutableStringWithCapacity(0)
NSInteger length = len( processStr )
for i = 0 to length - 1
CFStringRef temp = mid( processStr, i, 1 )
select ( temp )
case @"\n", @"\r"
MutableStringAppendString( mutStr, @"\n" )
case else
CFStringRef code = fn MorseCharacter( temp )
if ( code != NULL )
MutableStringAppendString( mutStr, fn StringByAppendingString( code, @" " ) )
else
MutableStringAppendString( mutStr, @" " )
end if
end select
next
end fn = fn StringWithString( mutStr )
local fn MorseCodeAudio( morseStr as CFStringRef )
NSInteger i
NSInteger length = len( morseStr )
for i = 0 to length - 1
CFStringRef temp = mid( morseStr, i, 1 )
fn ParseCodeAndPlay( temp )
next
end fn
local fn OutputMorseCode( morseStr as CFStringRef )
NSLog( @"\nSample ham radio Morse Code transmission:\n\n%@", morseStr )
CFStringRef codeStr = fn BuildMorseString( morseStr )
NSLog( @"\n\nMorse Code:\n\n%@", codeStr )
NSLog( @"\n\nAudio playing...\n" )
dispatchglobal
fn MorseCodeAudio( codeStr )
dispatchend
end fn
CFStringRef morseStr = @"CQ CQ CQ DE K1XYZ K1XYZ K TRANSMIT K1XYZ DE W1ZZZ TKS FOR CALL UR RST 479 479 NAME KEN KEN QTH NR KENTUCKY KENTUCKY G3ZZY DE W1ZZZ K"
fn OutputMorseCode( morseStr )
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Sample ham radio Morse Code transmission:
CQ CQ CQ DE K1XYZ K1XYZ K TRANSMIT K1XYZ DE W1ZZZ TKS FOR CALL UR RST 479 479 NAME KEN KEN QTH NR KENTUCKY KENTUCKY K1XYZ DE W1ZZZ K
Morse Code:
-.-. --.- -.-. --.- -.-. --.- -.. . -.- .---- -..- -.-- --.. -.- .---- -..- -.-- --.. -.- - .-. .- -. ... -- .. - -.- .---- -..- -.-- --.. -.. . .-- .---- --.. --.. --.. - -.- ... ..-. --- .-. -.-. .- .-.. .-.. ..- .-. .-. ... - ....- --... ----. ....- --... ----. -. .- -- . -.- . -. -.- . -. --.- - .... -. .-. -.- . -. - ..- -.-. -.- -.-- -.- . -. - ..- -.-. -.- -.-- --. ...-- --.. --.. -.-- -.. . .-- .---- --.. --.. --.. -.-
Audio playing...
-.-. --.- -.-. --.- -.-. --.- -.. . -.- .---- -..- -.
</pre>
=={{header|Gambas}}==
<
Public Sub Main()
Line 1,332 ⟶ 2,069:
Next
End</
Output (plus sound):
<pre>
Line 1,340 ⟶ 2,077:
=={{header|Go}}==
<
// showing the output on the console, and playing it as sound.
// Only works on ubuntu.
Line 1,493 ⟶ 2,230:
}
</syntaxhighlight>
=={{header|Haskell}}==
Line 1,502 ⟶ 2,239:
The main program.
<syntaxhighlight lang="haskell">
import System.IO
import MorseCode
Line 1,513 ⟶ 2,250:
text <- getContents
play $ toMorse text
</syntaxhighlight>
The module to convert text to Morse code symbols.
<syntaxhighlight lang="haskell">
module MorseCode (Morse, MSym(..), toMorse) where
Line 1,553 ⟶ 2,290:
fromChar = fromJust . flip M.lookup dict
weed = filter (\c -> c == ' ' || M.member c dict)
</syntaxhighlight>
The module to interpret Morse code symbols as sound.
<syntaxhighlight lang="haskell">
module MorsePlaySox (play) where
Line 1,596 ⟶ 2,333:
play :: Morse -> IO ExitCode
play = simple put none rate . concatMap toSamples
</syntaxhighlight>
=={{header|J}}==
<
morse=:[:; [:(' ',~' .-' {~ 3&#.inv)&.> (_96{.".0 :0-.LF) {~ a.&i.@toupper
79 448 0 1121 0 0 484 214 644 0 151 692 608 455 205 242 161 134 125 122
Line 1,608 ⟶ 2,345:
onoffdur=: 0.01*100<.@*(1.2%[)*(4 4#:2 5 13){~' .-'i.]
playmorse=: 30&$: :((wavnote&, 63 __"1)@(onoffdur morse))</
Example use:
<syntaxhighlight lang="text"> morse'this is an example'
- .... .. ... .. ... .- -. . -..- .- -- .--. .-.. .
playmorse'this is an example'
1
12 playmorse'as is this'
1</
morse converts from text to dot dash notation
Line 1,637 ⟶ 2,374:
=={{header|Java}}==
{{works with|java|7}}
<
public class MorseCode {
Line 1,680 ⟶ 2,417:
System.out.println("\n");
}
}</
<pre>sos
Line 1,695 ⟶ 2,432:
This implementation utilises the fairly new Web Audio API in the browser for generating tones, as such it only uses one vendor implementation (WebKit). It is split into three modules; 1. translating the characters into morse code. 2. creating timings for the morse code. 3. creating tones with the timings.
<syntaxhighlight lang="javascript">
var globalAudioContext = new webkitAudioContext();
Line 1,779 ⟶ 2,516:
return cont;
}
</syntaxhighlight>
Usage:
<syntaxhighlight lang="javascript">
morsecode('Hello World');
</syntaxhighlight>
{{out}}
[http://jsbin.com/orubaq/1/edit Live Version]
=={{header|Julia}}==
Requires a sound card and the PortAudio libraries.
<
const pstream = PortAudioStream(0, 2)
Line 1,825 ⟶ 2,561:
sendmorse("sos sos sos")
sendmorse("The case of letters in Morse coding is ignored."
</syntaxhighlight>
=={{header|Kotlin}}==
Line 1,831 ⟶ 2,567:
Java does not have easy access to the beep method, so we need to create one using the Audio API it provides.
<
import javax.sound.sampled.AudioSystem
Line 1,892 ⟶ 2,628:
playMorseCode(toMorseCode(it.toLowerCase()))
}
}</
=={{header|Liberty BASIC}}==
<
Input "Input the text to translate to Morse Code... "; string$
Print PlayMorse$(string$)
Line 1,949 ⟶ 2,685:
Data "@", ".--.-.", "(", "-.--.", ")", "-.--.-", "_", "..--.-", "$", "...-..-", "&", ".-..."
Data "=", "-...-", "!", "..--.", " ", " ", "End", ""
End Function </
=={{header|Lua}}==
The following code is actual eLua code used to beep the speaker in Morse code n the Shenzhou III STM32F103ZET6 evaluation board. eLua is a Lua 5.1.4 implementation paired with libraries for low-level hardware access in embedded systems. The below code could easily be converted to any other Lua 5.n environment (including games), provided some kind of sound library has been installed. Only the functions buzz and pause would have to be modified.
<
-- module-local variables
Line 2,046 ⟶ 2,782:
init(50000)
return M</
Using this module is as simple as:
<
morse.beep "I am the very model of a modern major-general."</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
A Morse "codec" based on replacement rule programming.
Replacement rules also translate the text Morse code into audible Morse code.
The dots and dashes become clarinet middle-C notes of different lengths.
Unknown characters encode into "?" in Morse text and clarinet F# in Morse audio.
The function, sonicMorse[s_String], plays the Morse code audio translation of a string.
<syntaxhighlight lang="mathematica">Dictionary = Join[CharacterRange["a", "z"], CharacterRange["0", "9"]];
mark = 0.1; gap = 0.125; (* gap should be equal to mark. But longer gap makes audio code easier to decode *)
shortgap = 3*gap; medgap = 7*gap;
longmark = 3*mark;
MorseDictionary = {
".-", "-...", "-.-.", "-..",
".", "..-.", "--.", "....", "..",
".---", "-.-", ".-..", "--", "-.",
"---", ".--.", "--.-", ".-.",
"...", "-", "..-", "...-", ".--",
"-..-", "-.--", "--..",
"-----", ".----", "..---", "...--", "....-", ".....",
"-....", "--...", "---..", "----."
};
MorseDictionary = # <> " " & /@ MorseDictionary; (* Force short gap silence after each letter/digit *)
Tones = {
SoundNote[None, medgap],
SoundNote[None, shortgap],
{SoundNote["C", mark, "Clarinet"], SoundNote[None, gap]},
{SoundNote["C", longmark, "Clarinet"], SoundNote[None, gap]},
{SoundNote["F#", mark, "Clarinet"], SoundNote[None, gap]} (* Use F# short mark to denote unrecognized character *)
};
codeRules = MapThread[Rule, {Dictionary, MorseDictionary}];
decodeRules = MapThread[Rule, {MorseDictionary, Dictionary}];
soundRules = MapThread[Rule, {{" ", " ", ".", "-", "?"}, Tones}];
(* The order of the rules here is important. Otherwise medium gaps and short gaps get confounded *)
morseCode[s_String] := StringReplace[ToLowerCase@s, codeRules~Join~{x_ /; FreeQ[Flatten@{Dictionary, " "}, x] -> "? "}]
morseDecode[s_String] := StringReplace[s, decodeRules]
sonicMorse[s_String] := EmitSound@Sound@Flatten[Characters@morseCode@s /. soundRules]</syntaxhighlight>
{{out|Text example}}
<pre>morseCode["SOS soS"]
morseDecode[%]
morseCode["s@os|"]</pre>
{{out}}
<pre>"... --- ... ... --- ... "
"sos sos"
"... ? --- ... ? "</pre>
=={{header|MATLAB}}==
This function will remove any characters not defined in the morse code.
<
%% Translate AlphaNumeric Text to Morse Text
Line 2,126 ⟶ 2,914:
end
end %text2morse</
{{out}} This will play the audio automatically, because the playSound argument is "true".
<
ans =
-.-.|.-|.-..|.-..| |--|.| |..|...|....|--|.-|.|.-..|</
=={{header|Modula-2}}==
<
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 2,250 ⟶ 2,985:
ReadChar;
END MorseCode.</
=={{header|Nim}}==
Text mode only. The text to translate is provided in the command line.
<syntaxhighlight lang="nim">import os, strutils, tables
const 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': "----.", '.': ".-.-.-", ',': "--..--", '?': "..--..", '\'': ".----.",
'!': "-.-.--", '/': "-..-.", '(': "-.--.", ')': "-.--.-", '&': ".-...",
':': "---...", ';': "-.-.-.", '=': "-...-", '+': ".-.-.", '-': "-....-",
'_': "..--.-", '"': ".-..-.", '$': "...-..-", '@': ".--.-."}.toTable
proc morse(s: string): string =
var r: seq[string]
for c in s:
r.add Morse.getOrDefault(c.toUpperAscii, "")
result = r.join(" ")
var m: seq[string]
for arg in commandLineParams():
m.add morse(arg)
echo m.join(" ")</syntaxhighlight>
{{out}}
<pre>./morse Hello World!
.... . .-.. .-.. --- .-- --- .-. .-.. -.. -.-.--</pre>
=={{header|OCaml}}==
Using <code>/dev/dsp</code>:
<
'a', ".-"; 'b', "-..."; 'c', "-.-.";
'd', "-.."; 'e', "."; 'f', "..-.";
Line 2,300 ⟶ 3,067:
| _ -> prerr_endline "unknown char")
let () = morse "rosettacode morse"</
=={{header|Ol}}==
Line 2,306 ⟶ 3,073:
To simplify the example will be used only lower letter case.
<syntaxhighlight lang="ol">
(display "Please, enter the string in lower case bounded by \" sign: ")
(lfor
Line 2,332 ⟶ 3,099:
; <== "hello world"
; ==> ......-...-..--- .-----.-..-..-..
</syntaxhighlight>
=={{header|PARI/GP}}==
<
while((ms-=gettime()) > 0,);
};
Line 2,349 ⟶ 3,116:
};
Morse("...---...")</
=={{header|Pascal}}==
Line 2,356 ⟶ 3,123:
This program uses OpenAL for cross-platform PCM audio.
<syntaxhighlight lang="pascal">
{$mode delphi}
PROGRAM cw;
Line 2,478 ⟶ 3,245:
AlutExit();
END.
</syntaxhighlight>
=={{header|Perl}}==
<
SetMorseVals(20,30,400);
SendMorseMsg('Hello World! abcdefg @\;'); # note, caps are ingnored in Morse Code
exit;</
The above code requires:
Line 2,495 ⟶ 3,262:
2) pcspkr may be available but muted.
- Check your sound prefrences,usually a right click over the speaker icon</pre>
=={{header|Phix}}==
With Baden-Powell menemonics.
{{libheader|Phix/pGUI}}
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/Morse_code.htm here].
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Morse_code.exw
-- ===========================
--</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #7060A8;">beep</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">input</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">output</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">vbox</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">dlg</span>
<span style="color: #004080;">cdCanvas</span> <span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">title</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Morse code"</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">help_text</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
Enter a message to
Press Return to listen to the result.
Characters A-Z are shown with Baden-Powell menemonics.
(Note said are a memory aid, not perfectly readable.)
Obviously deliberately looking away and listening
would be the best way to use this as a learning aid.
"""</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">show_help</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupMessage</span><span style="color: #0000FF;">(</span><span style="color: #000000;">title</span><span style="color: #0000FF;">,</span><span style="color: #000000;">help_text</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bWrap</span><span style="color: #0000FF;">:=</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetFocus</span><span style="color: #0000FF;">(</span><span style="color: #000000;">input</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_IGNORE</span> <span style="color: #000080;font-style:italic;">-- (don't open the browser help!)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">morse_data</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
!-.-.--#".-..-.#$...-..-#&.-...#'.----.#(-.--.#)-.--.-#+.-.-.#,--..--#--....-#..-.-.-#/-..-.#=-...-#
0-----#1.----#2..---#3...--#4....-#5.....#6-....#7--...#8---..#9----.#:---...#;-.-.-.#?..--..#@.--.-.#
A.-51517525#B-...7177414144444747#C-.-.7121121277271616#D-..717741414747#E.7474#F..-.7171111174247777#
G--.712177271818#H....2121717127277777#I..51515757#J.---2121222558269668#K-.-742184854428#(-.--.#
L.-..7171727677771717#M--45118155#N-.71362727#O---712182861216#P.--.8181612164247777#)-.--.-#
Q--.-8286121677775818#R.-.717144261717#S...515154545757#T-7121#U..-818111117727#V...-8181111156567727#
W.--818187534317#X-..-8154333365654518#Y-.--8163545433115558#Z--..7121762277771717#_..--.-# #"""</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">morse</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">``</span><span style="color: #0000FF;">,</span><span style="color: #000000;">255</span><span style="color: #0000FF;">),</span> <span style="color: #000080;font-style:italic;">-- the eg "..."'s</span>
<span style="color: #000000;">bdnpwl</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">({},</span><span style="color: #000000;">255</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- Baden-Powell mnemonics</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">setMorse</span><span style="color: #0000FF;">()</span>
<span style="color: #000080;font-style:italic;">-- I trust the characters and morse codes are all pretty evident in morse_data.
-- Baden-Powell mnemonics are encoded as 4 points on a 9wx7h grid per dot/dash,
-- counting (it just turned out that way) right to left and top to bottom, such
-- that "9711" (=1197) is(/looks like) a forwardslash and "9117" a backslash.
-- Each quite fiddly to set up - rather relieved there were only 26 of them!</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">data</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">morse_data</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">""</span><span style="color: #0000FF;">),</span><span style="color: #008000;">'#'</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">di</span> <span style="color: #008080;">in</span> <span style="color: #000000;">data</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">key</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">di</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">bpm</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">trim_head</span><span style="color: #0000FF;">(</span><span style="color: #000000;">di</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..$],</span><span style="color: #008000;">".- "</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">code</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">di</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..-</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bpm</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bpm</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">or</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bpm</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">4</span><span style="color: #0000FF;">*</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">code</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">morse</span><span style="color: #0000FF;">[</span><span style="color: #000000;">key</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">code</span> <span style="color: #000080;font-style:italic;">-- eg morse['S'] = "..."</span>
<span style="color: #000000;">bdnpwl</span><span style="color: #0000FF;">[</span><span style="color: #000000;">key</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_sub</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'5'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bpm</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">morse</span><span style="color: #0000FF;">[</span><span style="color: #008000;">'['</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">morse</span><span style="color: #0000FF;">[</span><span style="color: #008000;">'('</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">morse</span><span style="color: #0000FF;">[</span><span style="color: #008000;">']'</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">morse</span><span style="color: #0000FF;">[</span><span style="color: #008000;">')'</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">setMorse</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">redraw_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">text</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">upper</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupGetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">input</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">)),</span>
<span style="color: #000000;">outstr</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">dw</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dh</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetIntInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"DRAWSIZE"</span><span style="color: #0000FF;">),</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">tw</span><span style="color: #0000FF;">,</span><span style="color: #000000;">th</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCanvasGetTextSize</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span><span style="color: #000000;">text</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">tw</span><span style="color: #0000FF;">></span><span style="color: #000000;">dw</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">outstr</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000000;">outstr</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">" "</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">outstr</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">morse</span><span style="color: #0000FF;">[</span><span style="color: #000000;">text</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]]</span>
<span style="color: #000000;">text</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">text</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..$]</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">tw</span><span style="color: #0000FF;">,</span><span style="color: #000000;">th</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCanvasGetTextSize</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span><span style="color: #000000;">text</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">cw</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tw</span><span style="color: #0000FF;">/</span><span style="color: #7060A8;">max</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">text</span><span style="color: #0000FF;">),</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">cx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">dw</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">cy</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">dh</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span>
<span style="color: #7060A8;">cdCanvasActivate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasSetBackground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_LIGHT_PARCHMENT</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasClear</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasSetForeground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">#BBADA0</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasText</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cx</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cy</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">text</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">cx</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">cw</span><span style="color: #0000FF;">*(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">text</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">-</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasSetForeground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_BLUE</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasSetLineWidth</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCanvasMarkSize</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">gw</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">cw</span><span style="color: #0000FF;">*</span><span style="color: #000000;">0.75</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">gh</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">th</span><span style="color: #0000FF;">*</span><span style="color: #000000;">0.285</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">ch</span> <span style="color: #008080;">in</span> <span style="color: #000000;">text</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">bpm</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">bdnpwl</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bpm</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bpm</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">by</span> <span style="color: #000000;">4</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">x1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">cx</span><span style="color: #0000FF;">+</span><span style="color: #000000;">gw</span><span style="color: #0000FF;">*</span><span style="color: #000000;">bpm</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">+</span><span style="color: #000000;">0</span><span style="color: #0000FF;">]/</span><span style="color: #000000;">8</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">y1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">cy</span><span style="color: #0000FF;">+</span><span style="color: #000000;">gh</span><span style="color: #0000FF;">*</span><span style="color: #000000;">bpm</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]/</span><span style="color: #000000;">4</span><span style="color: #0000FF;">-</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">x2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">cx</span><span style="color: #0000FF;">+</span><span style="color: #000000;">gw</span><span style="color: #0000FF;">*</span><span style="color: #000000;">bpm</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]/</span><span style="color: #000000;">8</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">y2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">cy</span><span style="color: #0000FF;">+</span><span style="color: #000000;">gh</span><span style="color: #0000FF;">*</span><span style="color: #000000;">bpm</span><span style="color: #0000FF;">[</span><span style="color: #000000;">k</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]/</span><span style="color: #000000;">4</span><span style="color: #0000FF;">-</span><span style="color: #000000;">3</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">x1</span><span style="color: #0000FF;">=</span><span style="color: #000000;">x2</span> <span style="color: #008080;">and</span> <span style="color: #000000;">y1</span><span style="color: #0000FF;">=</span><span style="color: #000000;">y2</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">cdCanvasMark</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #7060A8;">cdCanvasLine</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">cx</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">cw</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">outstr</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #000000;">outstr</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">" "</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">outstr</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">morse</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">cdCanvasFlush</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">output</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">outstr</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">map_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">cdcanvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_IUP</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">cddbuffer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_DBUFFER</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- cdCanvasFont(cddbuffer,"Courier",CD_PLAIN,24)</span>
<span style="color: #7060A8;">cdCanvasFont</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Courier"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">CD_PLAIN</span><span style="color: #0000FF;">,</span><span style="color: #000000;">48</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasSetTextAlignment</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_CENTER</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">frequency</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1280</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- in Hz, 37..32767</span>
<span style="color: #000000;">wpm</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">15</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- words per minute</span>
<span style="color: #000000;">dit</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1200</span><span style="color: #0000FF;">/</span><span style="color: #000000;">wpm</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">-- in milliseconds</span>
<span style="color: #000000;">dah</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">*</span><span style="color: #000000;">dit</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">lettergap</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">*</span><span style="color: #000000;">dit</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">wordgap</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">*</span><span style="color: #000000;">dit</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">key_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*dlg*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #004600;">K_ESC</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CLOSE</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- (standard practice for me)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #004600;">K_F5</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- (let browser reload work)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #004600;">K_F1</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">show_help</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #004600;">K_CR</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">text</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">trim</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">upper</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupGetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">input</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">)))</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">durations</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">ch</span> <span style="color: #008080;">in</span> <span style="color: #000000;">text</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">=</span><span style="color: #008000;">' '</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">durations</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">wordgap</span>
<span style="color: #008080;">else</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">durations</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">durations</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">lettergap</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">morse</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">></span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #000000;">durations</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">dit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">durations</span> <span style="color: #0000FF;">&=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]=</span><span style="color: #008000;">'.'</span><span style="color: #0000FF;">?</span><span style="color: #000000;">dit</span><span style="color: #0000FF;">:</span><span style="color: #000000;">dah</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">beep</span><span style="color: #0000FF;">(</span><span style="color: #000000;">frequency</span><span style="color: #0000FF;">,</span><span style="color: #000000;">durations</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0.5</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">input</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"SELECTION"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ALL"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">elsif</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"#"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">beep</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_IGNORE</span>
<span style="color: #008080;">else</span>
<span style="color: #7060A8;">IupUpdate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">input</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupText</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"EXPAND=HORIZONTAL"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">canvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupCanvas</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"RASTERSIZE=520x40"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">output</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">""</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"EXPAND=HORIZONTAL"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">vbox</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">input</span><span style="color: #0000FF;">,</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span><span style="color: #000000;">output</span><span style="color: #0000FF;">},</span> <span style="color: #008000;">"MARGIN=10x5, GAP=5"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">vbox</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`TITLE="%s",MINSIZE=440x140`</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">title</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">IupSetCallback</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"KEY_CB"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"key_cb"</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">IupSetCallbacks</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"MAP_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"map_cb"</span><span style="color: #0000FF;">),</span>
<span style="color: #008000;">"ACTION"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"redraw_cb"</span><span style="color: #0000FF;">)})</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"RASTERSIZE"</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">NULL</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttributeHandle</span><span style="color: #0000FF;">(</span><span style="color: #004600;">NULL</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"PARENTDIALOG"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
=={{header|PicoLisp}}==
The following simply uses the 'beep' pc-speaker beeper utility.
<
(balance '*Morse
Line 2,713 ⟶ 3,490:
(wait (- *Dah *Dit)) ) )
(morse "Hello world!")</
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
/* Sound Morse code via the PC buzzer. June 2011 */
MORSE: procedure options (main);
Line 2,767 ⟶ 3,544:
end send_morse;
END MORSE;</
=={{header|PowerShell}}==
This function is case insensitive, ignores all non-Morse characters and optionally displays the Morse code.
<syntaxhighlight lang="powershell">
function Send-MorseCode
{
Line 2,832 ⟶ 3,608:
}
}
</syntaxhighlight>
<syntaxhighlight lang="powershell">
Send-MorseCode -Message "S.O.S" -ShowCode
</syntaxhighlight>
{{Out}}
<pre>
... --- ...
</pre>
<syntaxhighlight lang="powershell">
"S.O.S", "Goodbye, cruel world!" | Send-MorseCode -ShowCode
</syntaxhighlight>
{{Out}}
<pre>
Line 2,850 ⟶ 3,626:
-.-. .-. ..- . .-..
.-- --- .-. .-.. -..
</pre>
=={{header|Prolog}}==
Runs in SWI Prolog, Edinburgh syntax
<syntaxhighlight lang="prolog">
% convert text to morse
% query text2morse(Text, Morse)
% where
% Text is string to convert
% Morse is Morse representation
% There is a space between chars and double space between words
%
text2morse(Text, Morse) :-
string_lower(Text, TextLower), % rules are in lower case
string_chars(TextLower, Chars), % convert string into list of chars
chars2morse(Chars, MorseChars), % convert each char into morse
string_chars(MorsePlusSpace, MorseChars), % append returned string list into single string
string_concat(Morse, ' ', MorsePlusSpace). % Remove trailing space
chars2morse([], "").
chars2morse([H|CharTail], Morse) :-
morse(H, M),
chars2morse(CharTail, MorseTail),
string_concat(M,' ', MorseSpace),
string_concat(MorseSpace, MorseTail, Morse).
% space
morse(' ', " ").
% letters
morse('a', ".-").
morse('b', "-...").
morse('c', "-.-.").
morse('d', "-..").
morse('e', ".").
morse('f', "..-.").
morse('g', "--.").
morse('h', "....").
morse('i', "..").
morse('j', ".---").
morse('k', "-.-").
morse('l', ".-..").
morse('m', "--").
morse('n', "-.").
morse('o', "---").
morse('p', ".--.").
morse('q', "--.-").
morse('r', ".-.").
morse('s', "...").
morse('t', "-").
morse('u', "..-").
morse('v', "...-").
morse('w', ".--").
morse('x', "-..-").
morse('y', "-.--").
morse('z', "--..").
% numbers
morse('1', ".----").
morse('2', "..---").
morse('3', "...--").
morse('4', "....-").
morse('5', ".....").
morse('6', "-....").
morse('7', "--...").
morse('8', "---..").
morse('9', "----.").
morse('0', "-----").
% common punctuation
morse('.', ".-.-.-").
morse(',', "--..--").
morse('/', "-..-.").
morse('?', "..--..").
morse('=', "-...-").
morse('+', ".-.-.").
morse('-', "-....-").
morse('@', ".--.-.").
</syntaxhighlight>
<syntaxhighlight lang="prolog">
text2morse("Hello World", Morse).
</syntaxhighlight>
{{Out}}
<pre>
Morse = ".... . .-.. .-.. --- .-- --- .-. .-.. -.."
</pre>
=={{header|PureBasic}}==
<
#Frequence=1250
#Short = #BaseTime
Line 2,981 ⟶ 3,839:
Data.s "Done",""
EndOfMorseCode:
EndDataSection</
=={{header|Python}}==
<
char2morse = {
Line 3,045 ⟶ 3,903:
while True:
windowsmorse(input('A string to change into morse: '))
</syntaxhighlight>
=={{header|Quackery}}==
Mac specific as Quackery sits on top of Python, which is not strong with cross-platform audio.
<syntaxhighlight lang="Quackery"> [ $ /
import subprocess
subprocess.run(["say",
string_from_stack()])
/ python ] is speak ( $ --> )
[ 3 times [ $ " " speak ] ] is pause ( --> )
[ [] swap witheach
[ char - = iff
[ $ "dash " join ]
else [ $ "dot " join ] ]
space join ] is dotdash ( $ --> $ )
[ table ] is letter ( n --> $ )
$ ".- -... -.-. -.. . ..-.
--. .... .. .--- -.-
.-.. -- -. --- .--.
--.- .-. ... - ..- ...-
.-- -..- -.-- --.."
nest$ witheach
[ dotdash ' letter put ]
[ table ] is number ( n --> $ )
$ "----- .---- ..--- ...--
....- ..... -.... --...
---.. ----."
nest$ witheach
[ dotdash ' number put ]
[ witheach
[ dup space = iff
[ drop pause ] done
dup char 0 char 9 1+
within iff
[ char 0 -
number speak ] done
upper
dup char A char Z 1+
within iff
[ char A -
letter speak ] done
drop ] ] is morse ( $ --> )</syntaxhighlight>
=={{header|Racket}}==
Using MIDI on Windows for the beeps.
<
#lang racket
(require ffi/unsafe ffi/unsafe/define)
Line 3,090 ⟶ 3,997:
(morse "Say something here")
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|rakudo|2015-09-24}}
Here we use the user as the audio device.
Just read the output, leaving extra pauses where indicated
by either whitespace or underscore.
<syntaxhighlight lang="raku" line>my %m = ' ', '_ _ ',
|<
! ---.
" .-..-.
$ ...-..-
' .----.
( -.--.
) -.--.-
+ .-.-.
, --..--
- -....-
. .-.-.-
/ -..-.
: ---...
; -.-.-.
= -...-
? ..--..
@ .--.-.
[ -.--.
] -.--.-
_ ..--.-
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 --..
>.map: -> $c, $m is copy {
$m.=subst(rx/'-'/, 'BGAAACK!!! ', :g);
$m.=subst(rx/'.'/, 'buck ', :g);
$c => $m ~ '_';
}
say prompt("Gimme a string: ").uc.comb.map: { %m{$_} // "<scratch> " }</syntaxhighlight>
Sample run:
<p>Gimme a string: <b>Howdy, World!</b>
<br>buck buck buck buck _ BGAAACK!!! BGAAACK!!! BGAAACK!!! _ buck BGAAACK!!! BGAAACK!!! _ BGAAACK!!! buck buck _ BGAAACK!!! buck BGAAACK!!! BGAAACK!!! _ BGAAACK!!! BGAAACK!!! buck buck BGAAACK!!! BGAAACK!!! _ _ _ buck BGAAACK!!! BGAAACK!!! _ BGAAACK!!! BGAAACK!!! BGAAACK!!! _ buck BGAAACK!!! buck _ buck BGAAACK!!! buck buck _ BGAAACK!!! buck buck _ BGAAACK!!! BGAAACK!!! BGAAACK!!! buck _
=={{header|Red}}==
Line 3,097 ⟶ 4,078:
or "red.exe -r morse.red " to compile to single .exe file <br>
each character will be printed with its corresponding code before played
<
file: %morse.red ;; filename, could be ommited
]
Line 3,157 ⟶ 4,138:
morse-text "rosetta code"
morse-text "hello world"
</syntaxhighlight>
<
file: %api.reds ;; filename, could be ommited
]
Line 3,183 ⟶ 4,164:
] [ wsleep duration ]
;;----------------------------------------------
</syntaxhighlight>
=={{header|REXX}}==
Line 3,212 ⟶ 4,193:
=={{header|Ring}}==
<
Line 3,270 ⟶ 4,251:
strmorse = left(strmorse,len(strmorse)-1)
see strmorse + nl
</syntaxhighlight>
Output:
<pre>
-|....|..|...| ..|...| .-| -|.|...|-| -|.|-..-|-
</pre>
=={{header|RPL}}==
We use here AWK's elegant way to store the Morse code.
≪ <span style="color:red">"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--."
440 0.1</span>
→ morse freq beat
≪ <span style="color:red">-56</span> CF <span style="color:grey">@ to be replaced by 51 SF on HP-28s</span>
<span style="color:red">1</span> OVER SIZE '''FOR''' j
morse OVER j DUP SUB
'''IF''' POS '''THEN'''
LAST
'''WHILE''' <span style="color:red">1</span> + ".-" morse 3 PICK DUP SUB POS '''REPEAT'''
LAST beat * freq SWAP BEEP
beat WAIT
'''END'''
DROP <span style="color:red">3</span>
'''ELSE''' <span style="color:red">5</span> '''END'''
beat * WAIT
'''NEXT'''
≫ ≫ '<span style="color:blue">EMIT</span>' STO
"SOS" <span style="color:blue">EMIT</span>
=={{header|Ruby}}==
{{works with|Ruby|1.8.7+}} (uses <code>each_char</code>)
{{libheader|win32-utils}}
<
class MorseCode
Line 3,343 ⟶ 4,347:
MorseCode.new('sos').send
MorseCode.new('this is a test.').send</
{{out}}
Line 3,353 ⟶ 4,357:
.-
- . ... - .-.-.-</pre>
=={{header|Rust}}==
Original code can be found on [https://github.com/Dragonrun1/morse_code GitHub].
morse_code/src/main.rs file:
<syntaxhighlight lang="rust">
//!
//! morse_code/src/main.rs
//!
//! Michael G. Cummings
//! 2019-08-26
//!
//! Since Rust doesn't have build-in audio support text output is used.
//!
use std::process;
use structopt::StructOpt;
use morse_code::{Config, Opt, run};
/// Core of the command-line binary.
///
/// By default expects input from stdin and outputs resulting morse code to stdout, but can also
/// read and/or write to files.
/// Use `morse_code --help` for more information about options.
fn main() {
let opts = Opt::from_args();
let mut config = Config::new(opts).unwrap_or_else(|err| {
eprintln!("Problem parsing arguments: {}", err);
process::exit(1);
});
if let Err(err) = run(&mut config) {
eprintln!("Application error: {}", err);
process::exit(2);
}
}
</syntaxhighlight>
morse_code/src/lib.rs file:
<syntaxhighlight lang="rust">
//!
//! morse_code/src/lib.rs
//!
//! Michael G. Cummings
//! 2019-08-26
//!
#[macro_use]
extern crate structopt;
use std::{fs, io};
use std::collections::HashMap;
use std::error::Error;
use std::path::PathBuf;
/// Main library function that does the actual work.
///
/// Each character has one space between them and there are two spaces between words.
/// Unknown characters in the input are replaced with a '#' in the output.
///
pub fn run(config: &mut Config) -> Result<(), Box<dyn Error>> {
let mut contents = String::new();
config.read.read_to_string(&mut contents)?;
let morse_map = init_code_map();
let mut result = String::new();
for char in contents.trim().to_uppercase().chars() {
match morse_map.get(&char) {
Some(hash) => {
result = result + *hash;
}
None => { result = result + "#" }
}
result = result + " ";
}
config.write.write(result.as_ref())?;
Ok(())
}
/// Configuration structure for the input and output streams.
#[derive(Debug)]
pub struct Config {
read: Box<dyn io::Read>,
write: Box<dyn io::Write>,
}
impl Config {
pub fn new(opts: Opt) -> Result<Config, &'static str> {
let input: Box<dyn io::Read> = match opts.input {
Some(p) => Box::new(fs::File::open(p).unwrap()),
None => Box::new(io::stdin()),
};
let output: Box<dyn io::Write> = match opts.output {
Some(p) => Box::new(fs::File::create(p).unwrap()),
None => Box::new(io::stdout()),
};
Ok(Config { read: input, write: output })
}
}
/// Structure used to hold command line opts(parameters) of binary.
///
/// Using StructOpt crate to parse command-line parameters/options.
///
#[derive(Debug, StructOpt)]
#[structopt(rename_all = "kebab-case", raw(setting = "structopt::clap::AppSettings::ColoredHelp"))]
pub struct Opt {
/// Input file, stdin if not present
#[structopt(short, long, parse(from_os_str))]
input: Option<PathBuf>,
/// Output file, stdout if not present
#[structopt(short, long, parse(from_os_str))]
output: Option<PathBuf>,
}
/// Initialize hash map of characters to morse code as string.
pub fn init_code_map() -> HashMap<char, &'static str> {
let mut morse_map: HashMap<char, &str> = HashMap::with_capacity(37);
morse_map.insert(' ', " ");
morse_map.insert('A', "._");
morse_map.insert('B', "_...");
morse_map.insert('C', "_._.");
morse_map.insert('D', "_..");
morse_map.insert('E', ".");
morse_map.insert('F', ".._.");
morse_map.insert('G', "__.");
morse_map.insert('H', "....");
morse_map.insert('I', "..");
morse_map.insert('J', ".___");
morse_map.insert('K', "_._");
morse_map.insert('L', "._..");
morse_map.insert('M', "__");
morse_map.insert('N', "_.");
morse_map.insert('O', "___");
morse_map.insert('P', ".__.");
morse_map.insert('Q', "__._");
morse_map.insert('R', "._.");
morse_map.insert('S', "...");
morse_map.insert('T', "_");
morse_map.insert('U', ".._");
morse_map.insert('V', "..._");
morse_map.insert('W', ".__");
morse_map.insert('X', "_.._");
morse_map.insert('Y', "_.__");
morse_map.insert('Z', "__..");
morse_map.insert('1', ".____");
morse_map.insert('2', "..___");
morse_map.insert('3', "...__");
morse_map.insert('4', "...._");
morse_map.insert('5', ".....");
morse_map.insert('6', "_....");
morse_map.insert('7', "__...");
morse_map.insert('8', "___..");
morse_map.insert('9', "____.");
morse_map.insert('0', "_____");
morse_map
}
</syntaxhighlight>
=={{header|Scala}}==
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/9Dsd74J/1 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/68KAarvEQQafYevTkWaCWg Scastie (remote JVM)].
<
private val code = Map(
Line 3,383 ⟶ 4,546:
printMorse("Rosetta Code")
}</
=={{header|sed}}==
Translation of AWK:
<
# Convert to uppercase
s/.*/\U&/
Line 3,396 ⟶ 4,560:
ta
# Remove lookup table
s/\n.*//</
Example:
<
$ echo hello world! | ./morse.sed
.... . .-.. .-.. --- .-- --- .-. .-.. -.. !</
=={{header|Tcl}}==
{{libheader|Snack}}
<
package require sound
Line 3,465 ⟶ 4,629:
set frequency 700
morse "Morse code with Tcl and Snack." 20</
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
MODE DATA
Line 3,502 ⟶ 4,666:
mc=EXCHANGE (mc,space2split)
BEEP $mc
</syntaxhighlight>
{{out}}
<pre>
Line 3,520 ⟶ 4,684:
=={{header|Ursa}}==
{{trans|Python}}
<
decl string<> chars
decl string<> morse
Line 3,616 ⟶ 4,780:
out "A string to change into morse: " console
encode_morse (in string console)
end while</
=={{header|VBA}}==
<
Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long
Line 3,679 ⟶ 4,843:
Sleep DELAY
Next i
End Sub</
{{out}}
Play the sound's morse and display :
Line 3,687 ⟶ 4,851:
{{works with|Visual Basic|6}}
The [[#VBA]] example works in VB6 as well, without any change.
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<syntaxhighlight lang="vbnet">Module Module1
Sub Main()
Dim word = "sos"
Dim codes As New Dictionary(Of String, String) From {
{"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", "----."}
}
For Each c In word.ToCharArray
Dim rslt = codes(c).Trim
For Each c2 In rslt.ToCharArray
If c2 = "." Then
Console.Beep(1000, 250)
Else
Console.Beep(1000, 750)
End If
System.Threading.Thread.Sleep(50)
Next
Next
End Sub
End Module</syntaxhighlight>
=={{header|Wren}}==
{{libheader|Wren-str}}
{{libheader|Wren-sound}}
As Wren-cli doesn't have any built-in audio support, we instead build a .wav file which can then be played using a utility such as rhythmbox or SoX, having first printed the morse code to the terminal for comparison.
Any characters which do not appear in the Morse alphabet are simply ignored.
<syntaxhighlight lang="wren">import "./str" for Str
import "./sound" for Wav
var charToMorse = {
"!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.",
"(": "-.--.", ")": "-.--.-", "+": ".-.-.", ",": "--..--",
"-": "-....-", ".": ".-.-.-", "/": "-..-.",
"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": "--..",
"[": "-.--.", "]": "-.--.-", "_": "..--.-"
}
var textToMorse = Fn.new { |text|
text = Str.upper(text)
var morse = ""
for (c in text) {
if (c == " ") {
morse = morse + (" " * 7)
} else {
var m = charToMorse[c]
if (m) morse = morse + m.join(" ") + " "
}
}
return morse.trimEnd()
}
var morse = textToMorse.call("Hello world!")
System.print(morse) // print to terminal
// now create a .wav file
morse = morse.replace("-", "...") // replace 'dash' with 3 'dot's
var data = []
var sampleRate = 44100
var samples = 0.2 * sampleRate // number of samples assuming 'dot' takes 200 ms.
var freq = 500 // say
var omega = 2 * Num.pi * freq
for (c in morse) {
if (c == ".") {
for (s in 0...samples) {
var value = (32 * (omega * s / sampleRate).sin).round & 255
data.add(value)
}
} else {
for (s in 0...samples) data.add(0)
}
}
Wav.create("morse_code.wav", data, sampleRate)</syntaxhighlight>
{{out}}
<pre>
. . . . . . - . . . - . . - - - . - - - - - . - . . - . . - . . - - - .
</pre>
<br>
It's also possible to play .wav files which (preferably) have a sample rate of 44.1 kHz using DOME:
{{libheader|DOME}}
<syntaxhighlight lang="wren">import "audio" for AudioEngine
class Main {
construct new() {}
init() {
AudioEngine.load("morse", "morse_code.wav")
AudioEngine.play("morse")
}
update() {}
draw(alpha) {}
}
var Game = Main.new()</syntaxhighlight>
=={{header|XPL0}}==
Line 3,695 ⟶ 4,980:
when its volume parameter is set to zero.
<
string 0; \use zero-terminated strings
Line 3,736 ⟶ 5,021:
CrLf(0);
Morse("Hello, world!");
]</
{{out}}
<pre>
Line 3,742 ⟶ 5,027:
H.... e. l.-.. l.-.. o--- ,--..-- w.-- o--- r.-. l.-.. d-.. !.-.-..
</pre>
=={{header|Yabasic}}==
Mixin classic/modern style. In Yabasic, line number is not mandatory.
<
20 DIM c$(54)
30 FOR f = 1 TO 54
Line 3,774 ⟶ 5,060:
1070 DATA "'",".____.","!","_._.__","/","_.._.","(","_.__.",")","_.__._"
1080 DATA "&","._...",":","___...",";","_._._.","=","_..._","+","._._.","-","_...._"
1090 DATA "_","..__._","\"","._.._.","$","..._.._","@",".__._."</
|