Advertisement
Guest User

Untitled

a guest
Mar 4th, 2013
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.28 KB | None | 0 0
  1. import math, wave, array, itertools, time, struct, msvcrt, sys
  2. import numpy, pyaudio
  3.  
  4. FREQUENCIES = [900, 800, 700, 666, 600, 500, 400]
  5.  
  6. def open_wav_file(path):
  7.     wav_file = wave.open(path, 'rb')
  8.     return {'file': wav_file,
  9.             'sample width': wav_file.getsampwidth(),
  10.             'channels': wav_file.getnchannels(),
  11.             'rate': wav_file.getframerate()}
  12.  
  13. def open_pyaudio_stream(wav_handle, is_output = True):
  14.    
  15.     p = pyaudio.PyAudio()
  16.    
  17.     stream = p.open(format = p.get_format_from_width(wav_handle['sample width']),
  18.                     channels = wav_handle['channels'],
  19.                     rate = wav_handle['rate'],
  20.                     output = is_output,
  21.                     input = not is_output)
  22.     return [stream, p]
  23.  
  24. def close_pyaudio_stream(stream, p):
  25.     stream.stop_stream()
  26.     stream.close()
  27.     p.terminate()
  28.    
  29. def read_wav_file(chunk_size, wav_handle):
  30.     wav_file = wav_handle['file']
  31.  
  32.     sample_width = wav_handle['sample width']
  33.     frame_rate = wav_handle['rate']
  34.  
  35.     data = wav_file.readframes(chunk_size)
  36.  
  37.     while len(data) == chunk_size * sample_width:
  38.         yield data
  39.         data = wav_file.readframes(chunk_size)
  40.     if data:
  41.         yield data
  42.  
  43. def write_wav_file(path, wav_handle, frames):
  44.     wav_file = wave.open(path, 'wb')
  45.    
  46.     wav_file.setnchannels(wav_handle['channels'])
  47.     wav_file.setsampwidth(2)
  48.     wav_file.setframerate(wav_handle['rate'])
  49.     wav_file.writeframes(b''.join(frames))
  50.     wav_file.close()
  51.    
  52. def play_wav_file(wav_handle):
  53.     chunk_size = 2048
  54.  
  55.     stream, p = open_pyaudio_stream(wav_handle)
  56.    
  57.     for wav_data in read_wav_file(chunk_size, wav_handle):
  58.         stream.write(wav_data)
  59.  
  60.     close_pyaudio_stream(stream, p)
  61.    
  62. def record_wav_file(path):
  63.     chunk_size = 1024
  64.  
  65.     wav_handle = {'channels': 1, 'sample width': 2, 'rate': 44100}
  66.    
  67.     stream, p = open_pyaudio_stream(wav_handle, is_output = False)
  68.  
  69.     frames = []
  70.  
  71.     while True:
  72.         try:
  73.             data = stream.read(chunk_size)
  74.             frames.append(data)
  75.         except KeyboardInterrupt:
  76.             write_wav_file(path, wav_handle, frames)
  77.             break
  78.            
  79.     close_pyaudio_stream(stream, p)
  80.  
  81. def write_abism_wav_file(abism_bin, path):
  82.    
  83.     frames = array.array('h')
  84.    
  85.     volume = 100
  86.     duration = 0.1
  87.     rate = 44100
  88.     samples = rate * duration
  89.  
  90.     wav_handle = {'channels': 1, 'sample width': 2, 'rate': 44100}
  91.    
  92.     for byte in abism_bin:
  93.         for bit in range(7):
  94.             if byte[bit] != '0':
  95.                 freq = FREQUENCIES[bit]
  96.                 for i in range(int(samples)):
  97.                     sample = 32767 * float(volume) / 100
  98.                     sample *= math.sin(math.pi * 2 * (i % int(rate / freq)) / int(rate / freq))
  99.                     frames.append(int(sample))
  100.                    
  101.     write_wav_file(path, wav_handle, frames.tostring())
  102.  
  103. def read_abism_wav_file(wav_handle):
  104.    
  105.     result = []
  106.  
  107.     chunk_size = 512
  108.     sample_width = wav_handle['sample width']
  109.     rate = wav_handle['rate']
  110.    
  111.     window = numpy.blackman(chunk_size)
  112.     freq_old = -1
  113.     byte = []
  114.  
  115.     for data in read_wav_file(chunk_size, wav_handle):
  116.         if len(data) == chunk_size * sample_width:
  117.             indata = numpy.array(wave.struct.unpack("%dh" % (len(data) / sample_width), data)) * window
  118.             fftData = abs(numpy.fft.rfft(indata)) ** 2
  119.             fft_max = fftData[1:].argmax() + 1
  120.  
  121.             if fft_max != len(fftData)-1:
  122.                 y0, y1, y2 = numpy.log(fftData[fft_max - 1:fft_max + 2:])
  123.                 x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)
  124.                 freq_current = (fft_max + x1) * rate / chunk_size
  125.             else:
  126.                 freq_current = fft_max * rate / chunk_size
  127.  
  128.             if not math.isnan(freq_current):
  129.                 freq_current = (round(freq_current, -1))
  130.                
  131.                 if freq_current in range(640, 671):
  132.                     freq_current = 666
  133.                 else:
  134.                     freq_current = round(freq_current, -2)
  135.                    
  136.                 freq_current = int(freq_current)
  137.                 if freq_current in FREQUENCIES:
  138.                     if freq_old != freq_current:
  139.                         bit = FREQUENCIES.index(freq_current)
  140.                         byte.append(bit)
  141.                         if bit == 6:
  142.                             result.append(''.join([str(int(i in byte)) for i in range(7)]))
  143.                             byte = []
  144.                             starting_freq = 0
  145.                     freq_old = freq_current
  146.     return result
  147.  
  148. def convert_to_abism_bin(text):
  149.     result = []
  150.     for c in text:
  151.         c1 = bin(ord(c) + 32)[2:][::-1]
  152.         if len(c1) == 8:
  153.             c1 = c1[1:]
  154.         result.append(c1)
  155.     return result
  156.  
  157.  
  158. def convert_from_abism_bin(abism_bin):
  159.     result1 = ''
  160.     result2 = ''
  161.     result3 = ''
  162.    
  163.     for byte in abism_bin:
  164.         result1 += chr(int(byte[::-1], 2) - 32)
  165.         result2 += chr(int(byte[::-1], 2))
  166.         result3 += chr(int(byte[:-1][::-1], 2))
  167.        
  168.     return result1#, result2, result3
  169.  
  170. def main():
  171.     agent_sys_output_recording = "agent sys output.wav"
  172.     user_input_recording = "user input.wav"
  173.    
  174.     while True:
  175.         try:
  176.             print 'Recording agent system output. Press CTRL+C to stop recording.'
  177.             record_wav_file(agent_sys_output_recording)
  178.  
  179.             wav_handle = open_wav_file(agent_sys_output_recording)
  180.             abism_output_data = read_abism_wav_file(wav_handle)
  181.             print 'Agent system output: ' + convert_from_abism_bin(abism_output_data)
  182.             wav_handle['file'].close()
  183.            
  184.             user_input_text = raw_input("Your input to system: ")
  185.             user_input_abism_bin = convert_to_abism_bin(user_input_text)
  186.             write_abism_wav_file(user_input_abism_bin, user_input_recording)
  187.  
  188.             wav_handle = open_wav_file(user_input_recording)
  189.             play_wav_file(wav_handle)
  190.             wav_handle['file'].close()
  191.            
  192.         except KeyboardInterrupt:
  193.             break
  194.  
  195. f = "2013-03-03 20-07 UTC - 202-999-3335 - 17011.wav"
  196. wav_handle = open_wav_file(f)
  197. d = read_abism_wav_file(wav_handle)
  198. print convert_from_abism_bin(d)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement