synth_common.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import numpy as np
  2. def readTrack(filename):
  3. header = True
  4. headerFields = {}
  5. data = []
  6. for ln in open(filename).read().split("\n"):
  7. if(ln=="EST_Header_End"):
  8. header = False
  9. numFrames = int(headerFields["NumFrames"])
  10. elif(header):
  11. h = ln.split(" ")
  12. headerFields[h[0]]=h[1]
  13. elif len(ln):
  14. d = ln.split(" ")
  15. a = float(d[0])
  16. b = int(d[1])
  17. c = float(d[2])
  18. data += [[a,b,c]]
  19. return headerFields,data
  20. def getPitch(d0,d1,pos):
  21. if(pos[1]==1): #voiced
  22. p = pos[0]
  23. for i in range(0,len(d0)-1):
  24. p0 = d0[i]
  25. p1 = d0[i+1]
  26. if(p0[0]<=p and p1[0]>p):
  27. interp = (p1[0]-p)/(p1[0]-p0[0])
  28. return p0[2]*interp+p1[2]*(1-interp)
  29. return 0;
  30. def calculate_windowed_waveform(x: np.ndarray, fs: int, f0: float, temporal_position: float) -> np.ndarray:
  31. half_window_length = int(fs / f0 + 0.5)
  32. base_index = np.arange(-half_window_length, half_window_length + 1)
  33. index = int(temporal_position * fs + 0.501) + 1.0 + base_index
  34. safe_index = np.minimum(len(x), np.maximum(1, index))
  35. safe_index = np.array(safe_index, dtype=np.int)
  36. # wave segments and set of windows preparation
  37. segment = x[safe_index - 1]
  38. time_axis = base_index / fs
  39. window = 0.5 * (np.cos(np.pi * time_axis * f0)) + 0.5
  40. return window*segment,safe_index
  41. def getImpulse(x,fs,f0,d1,p):
  42. for i in range(0,len(d1)-1):
  43. p0 = d1[i]
  44. p1 = d1[i+1]
  45. if(p0[0]<=p and p1[0]>p):
  46. interp = (p1[0]-p)/(p1[0]-p0[0])
  47. t0 = p0[0]
  48. t1 = p1[0]
  49. imp0,s0 = calculate_windowed_waveform(x,fs,f0,t0)
  50. imp1,s1 = calculate_windowed_waveform(x,fs,f0,t1)
  51. return imp0*interp+imp1*(1-interp)
  52. return None;