Advertisement
Guest User

Untitled

a guest
Dec 4th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import sys
  4. import subprocess
  5. from threading import Thread
  6.  
  7. ## Console
  8.  
  9. class Console(object):
  10.  
  11. @staticmethod
  12. def init():
  13. try:
  14. import termios
  15. Console.is_unix = True
  16. # Disable buffering
  17. Console.fd = sys.stdin.fileno()
  18. Console.oldattr = termios.tcgetattr(Console.fd)
  19. newattr = termios.tcgetattr(Console.fd)
  20. newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
  21. termios.tcsetattr(Console.fd, termios.TCSANOW, newattr)
  22. # Get getch
  23. Console.getch = lambda : sys.stdin.read(1)
  24. except ImportError:
  25. Console.is_unix = False
  26. # Get getch
  27. import msvcrt
  28. if sys.version_info.major == 2:
  29. Console.getch = msvcrt.getch
  30. else:
  31. Console.getch = lambda : msvcrt.getch().decode('utf-8')
  32.  
  33. @staticmethod
  34. def reset():
  35. if Console.is_unix:
  36. import termios
  37. termios.tcsetattr(Console.fd, termios.TCSANOW, Console.oldattr)
  38.  
  39. KEY_TIME = 0.3
  40.  
  41. KEY_TO_FREQ1 = {
  42. "a": 261.63,
  43. "w": 277.18,
  44. "s": 293.66,
  45. "e": 311.13,
  46. "d": 329.63,
  47. "f": 349.23,
  48. "t": 369.99,
  49. "g": 392.00,
  50. "y": 415.30,
  51. "h": 440.00,
  52. "u": 466.16,
  53. "j": 493.88,
  54. "k": 523.25,
  55. "o": 554.37,
  56. "l": 587.33,
  57. "p": 622.25,
  58. ";": 659.25,
  59. ":": 659.25,
  60. "'": 698.46,
  61. '"': 698.46,
  62. "]": 739.99,
  63. "}": 739.99,
  64. }
  65.  
  66. KEY_TO_FREQ = FREQ_TO_FREQ1
  67.  
  68. def play_sound(freq, time):
  69. proc = subprocess.Popen(['speaker-test', '--frequency', str(freq), '--test', 'sine'],
  70. stdout=subprocess.DEVNULL)
  71. try:
  72. proc.wait(timeout=time)
  73. except subprocess.TimeoutExpired:
  74. proc.kill()
  75.  
  76. class PlaySoundThread(Thread):
  77. def __init__(self, freq, time):
  78. Thread.__init__(self, daemon=True)
  79. self.freq = freq
  80. self.time = time
  81.  
  82. def run(self):
  83. play_sound(self.freq, self.time)
  84.  
  85. def play_char(ch):
  86. ch = ch.lower()
  87. if ch in KEY_TO_FREQ:
  88. PlaySoundThread(KEY_TO_FREQ[ch], KEY_TIME).start()
  89.  
  90. def print_char(ch):
  91. if ch == '\x7f':
  92. ch = '\b \b'
  93. elif ch == '\x04':
  94. raise EOFError
  95. print(ch, end='', flush=True)
  96.  
  97. def main():
  98. Console.init()
  99. try:
  100. while(True):
  101. ch = Console.getch()
  102. print_char(ch)
  103. play_char(ch)
  104. except (KeyboardInterrupt, EOFError):
  105. print()
  106. finally:
  107. Console.reset()
  108.  
  109. if __name__ == '__main__':
  110. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement