-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmorse.py
More file actions
100 lines (83 loc) · 2.61 KB
/
morse.py
File metadata and controls
100 lines (83 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import pygame
import sys
# global constants
FREQ = 44100 # same as audio CD
BITSIZE = -16 # unsigned 16 bit
CHANNELS = 2 # 1 == mono, 2 == stereo
BUFFER = 1024 # audio buffer size in no. of samples
FRAMERATE = 60 # how often to check if playback has finished
morsetab = {
'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': '----. ', ')': '-.--.- ',
' ': '|', '_': '..--.- ',
}
morse_sound = {
'.': 'dot.ogg',
'-': 'dash.ogg',
' ': 'short_silence.ogg',
'*': 'very_short_silence.ogg',
'|': 'long_silence.ogg',
}
pygame.init()
pygame.mixer.init(FREQ, BITSIZE, CHANNELS, BUFFER)
def main(argv):
convert_string = argv[0].lower()
play_morse_sound(code_to_sound_code(string_to_code(convert_string)))
print(string_to_code(convert_string).replace('|', ' '))
def playsound(soundfile):
"""Play sound through default mixer channel in blocking manner.
This will load the whole sound into memory before playback
"""
sound = pygame.mixer.Sound(soundfile)
clock = pygame.time.Clock()
sound.play()
while pygame.mixer.get_busy():
clock.tick(FRAMERATE)
def play_morse_sound(code):
for channel_id, dip in enumerate(code):
try:
sound = pygame.mixer.Sound(morse_sound[dip])
except KeyError:
sound = pygame.mixer.Sound(morse_sound[' '])
playsound(sound)
def code_to_sound_code(code):
res = code.replace('..', '.*.') \
.replace('--', '-*-') \
.replace('.-', '.*-') \
.replace('-.', '-*.') \
.replace('..', '.*.') \
.replace('--', '-*-') \
.replace('.-', '.*-') \
.replace('-.', '-*.')
return res
def string_to_code(convert_string):
res = ''
for c in convert_string:
try:
res += morsetab[c]
except KeyError:
pass
return res
if __name__ == '__main__':
main(sys.argv[1:])