这里需要使用pygame来发出声音。
import pygameimport timeimport syscode = {'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.5three_units = 3 * one_unitseven_units = 7 * one_unitpath = '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()
希望本文所述对大家的python程序设计有所帮助。
