Skip to content

Morse Code Translator

Abstract

Morse Code Translator is a Python application that provides bidirectional translation between regular text and Morse code. The application features a comprehensive Morse code dictionary, text-to-Morse conversion, Morse-to-text conversion, and audio playback functionality using system beeps. This project demonstrates dictionary manipulation, string processing, audio programming, and menu-driven interface design. It’s an excellent tool for learning Morse code and understanding historical communication methods.

Prerequisites

  • Python 3.6 or above
  • A code editor or IDE
  • Windows OS (for winsound module) or alternative audio library

Before you Start

Before starting this project, you must have Python installed on your computer. If you don’t have Python installed, you can download it from here. You must have a code editor or IDE installed on your computer. If you don’t have any code editor or IDE installed, you can download Visual Studio Code from here.

Note: This project uses the winsoundwinsound module which is Windows-specific. For other operating systems, you can modify the audio playback function to use alternative libraries like pygamepygame or playsoundplaysound.

Getting Started

Create a Project

  1. Create a folder named morse-code-translatormorse-code-translator.
  2. Open the folder in your favorite code editor or IDE.
  3. Create a file named morsecodetranslator.pymorsecodetranslator.py.
  4. Copy the given code and paste it in your morsecodetranslator.pymorsecodetranslator.py file.

Write the Code

  1. Copy and paste the following code in your morsecodetranslator.pymorsecodetranslator.py file.
⚙️ Morse Code Translator
Morse Code Translator
# Morse Code Translator
 
# Importing modules
import winsound
import time
import sys
 
# Defining variables
morse_code = {
    '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': '----.', ' ': ' ', ',': '--..--', '.': '.-.-.-', '?': '..--..',
    '/': '-..-.', '-': '-....-', '(': '-.--.', ')': '-.--.-'
}
 
# Defining functions
def translate_to_morse_code(text):
    morse_code_text = ''
    for letter in text:
        morse_code_text += morse_code[letter.upper()] + ' '
    return morse_code_text
 
def translate_to_text(morse_code_text):
    text = ''
    morse_code_text += ' '
    letter = ''
    for symbol in morse_code_text:
        if symbol != ' ':
            i = 0
            letter += symbol
        else:
            i += 1
            if i == 2:
                text += ' '
            else:
                text += list(morse_code.keys())[list(morse_code.values()).index(letter)]
                letter = ''
    return text
    
def play_morse_code(morse_code_text):
    for symbol in morse_code_text:
        if symbol == '.':
            winsound.Beep(1000, 100)
        elif symbol == '-':
            winsound.Beep(1000, 300)
        else:
            time.sleep(0.5)
            
def main():
    print('Morse Code Translator')
    print('1. Translate to Morse Code')
    print('2. Translate to Text')
    print('3. Play Morse Code')
    print('4. Exit')
    choice = input('Enter your choice: ')
    if choice == '1':
        text = input('Enter the text to translate to Morse Code: ')
        morse_code_text = translate_to_morse_code(text)
        print('Morse Code: ' + morse_code_text)
        main()
    elif choice == '2':
        morse_code_text = input('Enter the Morse Code to translate to Text: ')
        text = translate_to_text(morse_code_text)
        print('Text: ' + text)
        main()
    elif choice == '3':
        morse_code_text = input('Enter the Morse Code to play: ')
        play_morse_code(morse_code_text)
        main()
    elif choice == '4':
        sys.exit()
    else:
        print('Invalid choice')
        main()
        
# Calling main function
main()
 
Morse Code Translator
# Morse Code Translator
 
# Importing modules
import winsound
import time
import sys
 
# Defining variables
morse_code = {
    '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': '----.', ' ': ' ', ',': '--..--', '.': '.-.-.-', '?': '..--..',
    '/': '-..-.', '-': '-....-', '(': '-.--.', ')': '-.--.-'
}
 
# Defining functions
def translate_to_morse_code(text):
    morse_code_text = ''
    for letter in text:
        morse_code_text += morse_code[letter.upper()] + ' '
    return morse_code_text
 
def translate_to_text(morse_code_text):
    text = ''
    morse_code_text += ' '
    letter = ''
    for symbol in morse_code_text:
        if symbol != ' ':
            i = 0
            letter += symbol
        else:
            i += 1
            if i == 2:
                text += ' '
            else:
                text += list(morse_code.keys())[list(morse_code.values()).index(letter)]
                letter = ''
    return text
    
def play_morse_code(morse_code_text):
    for symbol in morse_code_text:
        if symbol == '.':
            winsound.Beep(1000, 100)
        elif symbol == '-':
            winsound.Beep(1000, 300)
        else:
            time.sleep(0.5)
            
def main():
    print('Morse Code Translator')
    print('1. Translate to Morse Code')
    print('2. Translate to Text')
    print('3. Play Morse Code')
    print('4. Exit')
    choice = input('Enter your choice: ')
    if choice == '1':
        text = input('Enter the text to translate to Morse Code: ')
        morse_code_text = translate_to_morse_code(text)
        print('Morse Code: ' + morse_code_text)
        main()
    elif choice == '2':
        morse_code_text = input('Enter the Morse Code to translate to Text: ')
        text = translate_to_text(morse_code_text)
        print('Text: ' + text)
        main()
    elif choice == '3':
        morse_code_text = input('Enter the Morse Code to play: ')
        play_morse_code(morse_code_text)
        main()
    elif choice == '4':
        sys.exit()
    else:
        print('Invalid choice')
        main()
        
# Calling main function
main()
 
  1. Save the file.
  2. Open the terminal in your code editor or IDE and navigate to the folder morse-code-translatormorse-code-translator.
command
C:\Users\Your Name\morse-code-translator> python morsecodetranslator.py
Morse Code Translator
1. Translate to Morse Code
2. Translate to Text
3. Play Morse Code
4. Exit
Enter your choice: 1
Enter the text to translate to Morse Code: HELLO
Morse Code: .... . .-.. .-.. --- 
 
Morse Code Translator
1. Translate to Morse Code
2. Translate to Text
3. Play Morse Code
4. Exit
Enter your choice: 2
Enter the Morse Code to translate to Text: .... . .-.. .-.. ---
Text: HELLO
 
Morse Code Translator
1. Translate to Morse Code
2. Translate to Text
3. Play Morse Code
4. Exit
Enter your choice: 3
Enter the Morse Code to play: ... --- ...
# Audio beeps will play the SOS pattern
command
C:\Users\Your Name\morse-code-translator> python morsecodetranslator.py
Morse Code Translator
1. Translate to Morse Code
2. Translate to Text
3. Play Morse Code
4. Exit
Enter your choice: 1
Enter the text to translate to Morse Code: HELLO
Morse Code: .... . .-.. .-.. --- 
 
Morse Code Translator
1. Translate to Morse Code
2. Translate to Text
3. Play Morse Code
4. Exit
Enter your choice: 2
Enter the Morse Code to translate to Text: .... . .-.. .-.. ---
Text: HELLO
 
Morse Code Translator
1. Translate to Morse Code
2. Translate to Text
3. Play Morse Code
4. Exit
Enter your choice: 3
Enter the Morse Code to play: ... --- ...
# Audio beeps will play the SOS pattern

Explanation

Morse Code Dictionary

The application uses a comprehensive dictionary mapping characters to Morse code:

morsecodetranslator.py
morse_code = {
    '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': '----.', ' ': ' ', ',': '--..--', '.': '.-.-.-', '?': '..--..',
    '/': '-..-.', '-': '-....-', '(': '-.--.', ')': '-.--.-'
}
morsecodetranslator.py
morse_code = {
    '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': '----.', ' ': ' ', ',': '--..--', '.': '.-.-.-', '?': '..--..',
    '/': '-..-.', '-': '-....-', '(': '-.--.', ')': '-.--.-'
}

Core Functions

1. Text to Morse Code Translation

morsecodetranslator.py
def translate_to_morse_code(text):
    morse_code_text = ''
    for letter in text:
        morse_code_text += morse_code[letter.upper()] + ' '
    return morse_code_text
morsecodetranslator.py
def translate_to_morse_code(text):
    morse_code_text = ''
    for letter in text:
        morse_code_text += morse_code[letter.upper()] + ' '
    return morse_code_text

2. Morse Code to Text Translation

morsecodetranslator.py
def translate_to_text(morse_code_text):
    text = ''
    morse_code_text += ' '
    letter = ''
    for symbol in morse_code_text:
        if symbol != ' ':
            i = 0
            letter += symbol
        else:
            i += 1
            if i == 2:
                text += ' '
            else:
                text += list(morse_code.keys())[list(morse_code.values()).index(letter)]
                letter = ''
    return text
morsecodetranslator.py
def translate_to_text(morse_code_text):
    text = ''
    morse_code_text += ' '
    letter = ''
    for symbol in morse_code_text:
        if symbol != ' ':
            i = 0
            letter += symbol
        else:
            i += 1
            if i == 2:
                text += ' '
            else:
                text += list(morse_code.keys())[list(morse_code.values()).index(letter)]
                letter = ''
    return text

3. Audio Playback Function

morsecodetranslator.py
def play_morse_code(morse_code_text):
    for symbol in morse_code_text:
        if symbol == '.':
            winsound.Beep(1000, 100)  # Short beep (dot)
        elif symbol == '-':
            winsound.Beep(1000, 300)  # Long beep (dash)
        else:
            time.sleep(0.5)  # Pause between letters
morsecodetranslator.py
def play_morse_code(morse_code_text):
    for symbol in morse_code_text:
        if symbol == '.':
            winsound.Beep(1000, 100)  # Short beep (dot)
        elif symbol == '-':
            winsound.Beep(1000, 300)  # Long beep (dash)
        else:
            time.sleep(0.5)  # Pause between letters

Features

  • Bidirectional Translation: Convert text to Morse code and Morse code back to text
  • Comprehensive Character Set: Supports letters, numbers, and common punctuation
  • Audio Playback: Listen to Morse code with system beeps
  • Menu-Driven Interface: Easy-to-use command-line menu system
  • Recursive Menu: Continuous operation until user chooses to exit
  • Case Insensitive: Handles both uppercase and lowercase input
  • Real-time Processing: Instant translation and playback

Morse Code Reference

Letters A-Z

LetterMorseLetterMorseLetterMorse
A.-J.---S
B-…K-.-T-
C-.-.L.-..U..-
D-..MV…-
E.N-.W.—
F..-O---X-..-
G—.P.—.Y-.—
HQ—.-Z—..
I..R.-.

Numbers 0-9

NumberMorse CodeNumberMorse Code
0-----5
1.----6-…
2..---7—…
3…—8---..
4…-9----.

Common Punctuation

SymbolMorse CodeSymbolMorse Code
..-.-.-(-.—.
,—..—)-.—.-
?..—..--…-
/-..-.

Audio Timing Standards

  • Dot (.): 100ms beep at 1000Hz
  • Dash (-): 300ms beep at 1000Hz
  • Letter spacing: 500ms pause
  • Word spacing: Represented by spaces in input

Use Cases

  • Emergency Communications: Learn SOS (… --- …) and other distress signals
  • Amateur Radio: Practice for ham radio licensing
  • Educational: Teaching communication history and methods
  • Military/Naval: Understanding maritime and military communications
  • Accessibility: Alternative communication method for specific needs

Next Steps

You can enhance this project by:

  • Adding a GUI interface with Tkinter or PyQt
  • Implementing adjustable playback speed and frequency
  • Adding visual Morse code display with flashing lights
  • Creating practice modes with random word generation
  • Adding file input/output for batch processing
  • Implementing prosigns (procedural signals) support
  • Adding Morse code keyboard input mode
  • Creating multiplayer Morse code games
  • Adding different audio tones and voices
  • Implementing Morse code over network communication

Cross-Platform Audio Support

For non-Windows systems, replace the audio function:

Using pygame (Cross-platform)

morsecodetranslator.py
import pygame
pygame.mixer.init()
 
def play_morse_code_pygame(morse_code_text):
    for symbol in morse_code_text:
        if symbol == '.':
            # Generate and play short tone
            play_tone(1000, 100)
        elif symbol == '-':
            # Generate and play long tone
            play_tone(1000, 300)
        else:
            time.sleep(0.5)
morsecodetranslator.py
import pygame
pygame.mixer.init()
 
def play_morse_code_pygame(morse_code_text):
    for symbol in morse_code_text:
        if symbol == '.':
            # Generate and play short tone
            play_tone(1000, 100)
        elif symbol == '-':
            # Generate and play long tone
            play_tone(1000, 300)
        else:
            time.sleep(0.5)

Using playsound (Cross-platform)

morsecodetranslator.py
from playsound import playsound
import tempfile
import wave
 
def create_morse_audio(morse_code_text):
    # Generate audio file and play
    pass
morsecodetranslator.py
from playsound import playsound
import tempfile
import wave
 
def create_morse_audio(morse_code_text):
    # Generate audio file and play
    pass

Educational Applications

  • Morse Code Learning: Interactive way to learn the code
  • Historical Education: Understanding telegraph communication
  • STEM Projects: Combining technology with history
  • Accessibility Training: Alternative communication methods
  • Emergency Preparedness: Learning distress signals

Advanced Features Ideas

morsecodetranslator.py
def enhanced_morse_translator():
    # Features to implement:
    # - GUI interface with visual indicators
    # - Adjustable speed and pitch
    # - Practice mode with scoring
    # - File batch processing
    # - Network transmission
    # - Visual light patterns
    pass
 
class MorseCodeTrainer:
    def __init__(self):
        self.difficulty_level = 1
        self.practice_words = []
        self.user_stats = {}
    
    def generate_practice_session(self):
        # Create random practice sessions
        pass
morsecodetranslator.py
def enhanced_morse_translator():
    # Features to implement:
    # - GUI interface with visual indicators
    # - Adjustable speed and pitch
    # - Practice mode with scoring
    # - File batch processing
    # - Network transmission
    # - Visual light patterns
    pass
 
class MorseCodeTrainer:
    def __init__(self):
        self.difficulty_level = 1
        self.practice_words = []
        self.user_stats = {}
    
    def generate_practice_session(self):
        # Create random practice sessions
        pass

Common Morse Code Phrases

  • SOS: … --- … (International distress signal)
  • CQ: -.-. —.- (General call to any station)
  • QRT: —.- .-. - (Stopping transmission)
  • 73: —… …— (Best wishes - amateur radio)

Performance Considerations

  • Memory Usage: Efficient dictionary lookup operations
  • Audio Quality: Consistent timing for clear communication
  • Response Time: Quick translation for real-time use
  • Error Handling: Graceful handling of invalid input

Educational Value

This project teaches:

  • Dictionary Operations: Key-value mapping and reverse lookup
  • String Processing: Character-by-character text manipulation
  • Audio Programming: System sound generation and timing
  • Menu Design: User interface and navigation logic
  • Historical Technology: Understanding communication evolution

Real-World Applications

  • Emergency Communication: Backup communication method
  • Amateur Radio: Ham radio operation and practice
  • Maritime Communication: Ship-to-shore signaling
  • Aviation: Aircraft communication protocols
  • Military Operations: Field communication training

Conclusion

In this project, we learned how to create a Morse Code Translator that demonstrates dictionary operations, string processing, and audio programming in Python. The application provides a practical tool for learning and practicing Morse code while showcasing fundamental programming concepts. This project bridges historical communication methods with modern programming techniques, offering both educational value and practical utility. To find more projects like this, you can visit Python Central Hub.

Was this page helpful?

Let us know how we did