Home > Backend Development > Python Tutorial > python实现带声音的摩斯码翻译实现方法

python实现带声音的摩斯码翻译实现方法

WBOY
Release: 2016-06-06 11:16:39
Original
1618 people have browsed it

本文实例讲述了python实现带声音的摩斯码翻译程序,分享给大家供大家参考。具体分析如下:

这里需要使用PyGame来发出声音。

import pygame
import time
import sys
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': '----.' 
    }
ONE_UNIT = 0.5
THREE_UNITS = 3 * ONE_UNIT
SEVEN_UNITS = 7 * ONE_UNIT
PATH = 'morse_sound_files/'
def verify(string):
  keys = CODE.keys()
  for char in string:
    if char.upper() not in keys and char != ' ':
      sys.exit('Error the charcter ' + char + ' cannot be translated to Morse Code')
def main():
  print 'Welcome to Alphabet to Morse Code Translator v.01\n'
  msg = raw_input('Enter Message: ')
  verify(msg)
  print
  pygame.init()
  for char in msg:
    if char == ' ':
      print ' '*7,
      time.sleep(SEVEN_UNITS)
    else:
      print CODE[char.upper()],
      pygame.mixer.music.load(PATH + char.upper() + '_morse_code.ogg')
      pygame.mixer.music.play()
      time.sleep(THREE_UNITS)
if __name__ == "__main__":
  main()

Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template