nadando

Untitled

May 10th, 2013
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.77 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. import math, wave, array, itertools, time, struct, msvcrt, sys
  3. import numpy, pyaudio
  4.  
  5. FREQUENCIES = [900, 800, 700, 666, 600, 500, 400]
  6.  
  7. def open_wav_file(path):
  8. wav_file = wave.open(path, 'rb')
  9. return {'file': wav_file,
  10. 'sample width': wav_file.getsampwidth(),
  11. 'channels': wav_file.getnchannels(),
  12. 'rate': wav_file.getframerate()}
  13.  
  14. def open_pyaudio_stream(wav_handle, is_output = True):
  15.  
  16. p = pyaudio.PyAudio()
  17.  
  18. stream = p.open(format = p.get_format_from_width(wav_handle['sample width']),
  19. channels = wav_handle['channels'],
  20. rate = wav_handle['rate'],
  21. output = is_output,
  22. input = not is_output)
  23. return [stream, p]
  24.  
  25. def close_pyaudio_stream(stream, p):
  26. stream.stop_stream()
  27. stream.close()
  28. p.terminate()
  29.  
  30. def read_wav_file(chunk_size, wav_handle):
  31. wav_file = wav_handle['file']
  32.  
  33. sample_width = wav_handle['sample width']
  34. frame_rate = wav_handle['rate']
  35.  
  36. data = wav_file.readframes(chunk_size)
  37.  
  38. while len(data) == chunk_size * sample_width:
  39. yield data
  40. data = wav_file.readframes(chunk_size)
  41. if data:
  42. yield data
  43.  
  44. def write_wav_file(path, wav_handle, frames):
  45. wav_file = wave.open(path, 'wb')
  46.  
  47. wav_file.setnchannels(wav_handle['channels'])
  48. wav_file.setsampwidth(2)
  49. wav_file.setframerate(wav_handle['rate'])
  50. wav_file.writeframes(b''.join(frames))
  51. wav_file.close()
  52.  
  53. def play_wav_file(wav_handle):
  54. chunk_size = 2048
  55.  
  56. stream, p = open_pyaudio_stream(wav_handle)
  57.  
  58. for wav_data in read_wav_file(chunk_size, wav_handle):
  59. stream.write(wav_data)
  60.  
  61. close_pyaudio_stream(stream, p)
  62.  
  63. def record_wav_file(path):
  64. chunk_size = 8
  65.  
  66. wav_handle = {'channels': 1, 'sample width': 2, 'rate': 44100}
  67.  
  68. stream, p = open_pyaudio_stream(wav_handle, is_output = False)
  69.  
  70. frames = []
  71.  
  72. while True:
  73. try:
  74. data = stream.read(chunk_size)
  75. frames.append(data)
  76. except KeyboardInterrupt:
  77. write_wav_file(path, wav_handle, frames)
  78. break
  79.  
  80. close_pyaudio_stream(stream, p)
  81.  
  82. def write_abism_wav_file(abism_bin, path):
  83.  
  84. frames = array.array('h')
  85.  
  86. volume = 100
  87. duration = 0.1
  88. rate = 44100
  89. samples = rate * duration
  90.  
  91. wav_handle = {'channels': 1, 'sample width': 2, 'rate': 44100}
  92.  
  93. for byte in abism_bin:
  94. for bit in range(7):
  95. if byte[bit] != '0':
  96. freq = FREQUENCIES[bit]
  97. for i in range(int(samples)):
  98. sample = 32767 * float(volume) / 100
  99. sample *= math.sin(math.pi * 2 * (i % int(rate / freq)) / int(rate / freq))
  100. frames.append(int(sample))
  101.  
  102. write_wav_file(path, wav_handle, frames.tostring())
  103.  
  104. def read_abism_wav_file(wav_handle):
  105.  
  106. result = []
  107.  
  108. chunk_size = 512
  109. sample_width = wav_handle['sample width']
  110. rate = wav_handle['rate']
  111.  
  112. window = numpy.blackman(chunk_size)
  113. freq_old = -1
  114. byte = []
  115.  
  116. for data in read_wav_file(chunk_size, wav_handle):
  117. if len(data) == chunk_size * sample_width:
  118. indata = numpy.array(wave.struct.unpack("%dh" % (len(data) / sample_width), data)) * window
  119. fftData = abs(numpy.fft.rfft(indata)) ** 2
  120. fft_max = fftData[1:].argmax() + 1
  121.  
  122. if fft_max != len(fftData)-1:
  123. y0, y1, y2 = numpy.log(fftData[fft_max - 1:fft_max + 2:])
  124. x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)
  125. freq_current = (fft_max + x1) * rate / chunk_size
  126. else:
  127. freq_current = fft_max * rate / chunk_size
  128.  
  129. if not math.isnan(freq_current):
  130. freq_current = (round(freq_current, -1))
  131.  
  132. if freq_current in range(640, 671):
  133. freq_current = 666
  134. else:
  135. freq_current = round(freq_current, -2)
  136.  
  137. freq_current = int(freq_current)
  138. if freq_current in FREQUENCIES:
  139. if freq_old != freq_current:
  140. bit = FREQUENCIES.index(freq_current)
  141. byte.append(bit)
  142. if bit == 6:
  143. result.append(''.join([str(int(i in byte)) for i in range(7)]))
  144. byte = []
  145. starting_freq = 0
  146. freq_old = freq_current
  147. return result
  148.  
  149. def convert_to_abism_bin(text):
  150. symbols = ['[NULL]', '!', "'", '#', '[SQUARE]',
  151. '%', '&', '"', '(', ')',
  152. '*', '+', ',', '-', '.',
  153. '/', '0', '1', '2', '3',
  154. '4', '5', '6', '7', '8',
  155. '9',
  156. '[unk]', '[unk]', '[unk]', '[unk]', '[unk]', '[unk]',
  157. ' ', 'A', 'B', 'C',
  158. 'D', 'E', 'F', 'G', 'H',
  159. 'I', 'J', 'K', 'L', 'M',
  160. 'N', 'O', 'P', 'Q', 'R',
  161. 'S', 'T', 'U', 'V', 'W',
  162. 'X', 'Y', 'Z', '[', '[CR]',
  163. ']', '[ESC]', '[LF]', 'Å', 'Α',
  164. 'Β', 'Ψ', 'Δ', 'Ε', 'Φ',
  165. 'Γ', 'Η', 'Ι', 'Ξ', 'Κ',
  166. 'Λ', 'Μ', 'Ν', 'Ο', 'Π',
  167. 'Æ', 'Ρ', 'Σ', 'Τ', 'Θ',
  168. 'Ω', 'Œ', 'Χ', 'Υ', 'Ζ',
  169. 'ß', 'Ç', 'Ø', 'Đ', 'þ',
  170. 'Ъ', 'А', 'Б', 'Ц', 'Д',
  171. 'Е', 'Ф', 'Г', 'Ч', 'И',
  172. 'Й', 'К', 'Л', 'М', 'Н',
  173. 'О', 'П', 'Я', 'Р', 'С',
  174. 'Т', 'У', 'В', 'Ш', 'Х',
  175. 'Ы', 'З', 'Ю', 'Ж', 'Э']
  176. result = []
  177. for c in text:
  178. if c in symbols:
  179. i = bin(symbols.index(c))[2:]
  180. i = ('0' * (7 - len(i))) + i
  181. result.append(i)
  182. else:
  183. return -1
  184. return result
  185.  
  186. result = []
  187. for c in text:
  188. #c1 = bin(ord(c) + 32)[2:][::-1]
  189. #c1 = ('1' + bin(ord(c))[2:])[::-1]
  190. c1 = (bin(ord(c))[2:])[::-1] + '1'
  191. if len(c1) == 8:
  192. c1 = c1[1:]
  193. result.append(c1)
  194. return result
  195.  
  196. def convert_from_abism_bin(abism_bin):
  197. #result1 = ''
  198. result2 = ''
  199. result3 = ''
  200.  
  201. for byte in abism_bin:
  202. #result1 += chr(int(byte[::-1], 2) - 32)
  203. result2 += chr(int(byte[::-1], 2))
  204. result3 += chr(int(byte[:-1][::-1], 2))
  205.  
  206. return result2, result3
  207.  
  208. def main():
  209. agent_sys_output_recording = "agent sys output.wav"
  210. user_input_recording = "user input.wav"
  211.  
  212. while True:
  213. try:
  214. print 'Recording agent system output. Press CTRL+C to stop recording.'
  215. record_wav_file(agent_sys_output_recording)
  216.  
  217. wav_handle = open_wav_file(agent_sys_output_recording)
  218. abism_output_data = read_abism_wav_file(wav_handle)
  219. print abism_output_data
  220. print 'Agent system output: ' + convert_from_abism_bin(abism_output_data)
  221. wav_handle['file'].close()
  222.  
  223. user_input_text = raw_input("Your input to system: ")
  224. user_input_abism_bin = convert_to_abism_bin(user_input_text)
  225. write_abism_wav_file(user_input_abism_bin, user_input_recording)
  226.  
  227. wav_handle = open_wav_file(user_input_recording)
  228. play_wav_file(wav_handle)
  229. wav_handle['file'].close()
  230.  
  231. except KeyboardInterrupt:
  232. break
  233.  
  234. #main()
  235. f = 'Vocaroo_s1U78CHfUpXi.wav'
  236. handle = open_wav_file(f)
  237. abin = read_abism_wav_file(handle)
  238. print convert_from_abism_bin(abin)
Advertisement
Add Comment
Please, Sign In to add comment