from numpy import*
from scipy.io.wavfile import read
from scipy.io.wavfile import write
# import matplotlib.pyplot as plt
import scipy
import sounddevice as sd
import time

# a = read("/home/jreinking/Projekte/doorbell/raspberry-pi-projects/res/klingel_aufnahme_microphne_cut.wav")
# print(a)
# print(len(a[1]))
# a = a[1]

def chunks(lst, n):
  """Yield successive n-sized chunks from lst."""
  for i in range(0, len(lst), n):
    yield lst[i:i + n]


def compress(a):
  a = chunks(a, 700)
  a = list(map(lambda x : mean(x), a))
  return a

def dtw(s, t):
  n, m = len(s), len(t)
  dtw_matrix = np.zeros((n+1, m+1))
  for i in range(n+1):
    for j in range(m+1):
      dtw_matrix[i, j] = np.inf
  dtw_matrix[0, 0] = 0
  
  for i in range(1, n+1):
    for j in range(1, m+1):
      cost = abs(s[i-1] - t[j-1])
      # take last min from a square box
      last_min = np.min([dtw_matrix[i-1, j], dtw_matrix[i, j-1], dtw_matrix[i-1, j-1]])
      dtw_matrix[i, j] = cost + last_min
  return dtw_matrix

# m = dtw(a, a)
# print(m)

NUMBER_OF_SNIPPETS = 5
SAMPLE_RATE = 44200
SECONDS = (400000 / SAMPLE_RATE) / NUMBER_OF_SNIPPETS

snippets = []
i = 0
while True:
  myrecording = sd.rec(int(SECONDS * SAMPLE_RATE), samplerate=SAMPLE_RATE, channels=2)
  snippets.append(myrecording)
  sd.wait()

  if len(snippets) > NUMBER_OF_SNIPPETS:
    snippets = snippets[1:]
    c = scipy.vstack(snippets)
    write("sample_{}.wav".format(i), SAMPLE_RATE, c)
    i += 1
    #c = compress(c)
    #plt.plot(c)
    #plt.show()
    # print(c)
    # print(len(list(map(lambda x : x[0], c))))
    # sd.play(c, SAMPLE_RATE)
    # sd.wait()



