audio.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import librosa
  2. import librosa.filters
  3. import numpy as np
  4. from scipy import signal
  5. from scipy.io import wavfile
  6. import soundfile as sf
  7. def load_wav(path, sr):
  8. return librosa.core.load(path, sr=sr)[0]
  9. def save_wav(wav, path, sr):
  10. wav *= 32767 / max(0.01, np.max(np.abs(wav)))
  11. #proposed by @dsmiller
  12. wavfile.write(path, sr, wav.astype(np.int16))
  13. def save_wavenet_wav(wav, path, sr):
  14. sf.write(path, wav.astype(np.float32), sr)
  15. def preemphasis(wav, k, preemphasize=True):
  16. if preemphasize:
  17. return signal.lfilter([1, -k], [1], wav)
  18. return wav
  19. def inv_preemphasis(wav, k, inv_preemphasize=True):
  20. if inv_preemphasize:
  21. return signal.lfilter([1], [1, -k], wav)
  22. return wav
  23. #From https://github.com/r9y9/wavenet_vocoder/blob/master/audio.py
  24. def start_and_end_indices(quantized, silence_threshold=2):
  25. for start in range(quantized.size):
  26. if abs(quantized[start] - 127) > silence_threshold:
  27. break
  28. for end in range(quantized.size - 1, 1, -1):
  29. if abs(quantized[end] - 127) > silence_threshold:
  30. break
  31. assert abs(quantized[start] - 127) > silence_threshold
  32. assert abs(quantized[end] - 127) > silence_threshold
  33. return start, end
  34. def get_hop_size(hparams):
  35. hop_size = hparams.hop_size
  36. if hop_size is None:
  37. assert hparams.frame_shift_ms is not None
  38. hop_size = int(hparams.frame_shift_ms / 1000 * hparams.sample_rate)
  39. return hop_size
  40. def linearspectrogram(wav, hparams):
  41. D = _stft(preemphasis(wav, hparams.preemphasis, hparams.preemphasize), hparams)
  42. S = _amp_to_db(np.abs(D), hparams) - hparams.ref_level_db
  43. if hparams.signal_normalization:
  44. return _normalize(S, hparams)
  45. return S
  46. def melspectrogram(wav, hparams):
  47. D = _stft(preemphasis(wav, hparams.preemphasis, hparams.preemphasize), hparams)
  48. S = _amp_to_db(_linear_to_mel(np.abs(D), hparams), hparams) - hparams.ref_level_db
  49. if hparams.signal_normalization:
  50. return _normalize(S, hparams)
  51. return S
  52. def inv_linear_spectrogram(linear_spectrogram, hparams):
  53. """Converts linear spectrogram to waveform using librosa"""
  54. if hparams.signal_normalization:
  55. D = _denormalize(linear_spectrogram, hparams)
  56. else:
  57. D = linear_spectrogram
  58. S = _db_to_amp(D + hparams.ref_level_db) #Convert back to linear
  59. if hparams.use_lws:
  60. processor = _lws_processor(hparams)
  61. D = processor.run_lws(S.astype(np.float64).T ** hparams.power)
  62. y = processor.istft(D).astype(np.float32)
  63. return inv_preemphasis(y, hparams.preemphasis, hparams.preemphasize)
  64. else:
  65. return inv_preemphasis(_griffin_lim(S ** hparams.power, hparams), hparams.preemphasis, hparams.preemphasize)
  66. def inv_mel_spectrogram(mel_spectrogram, hparams):
  67. """Converts mel spectrogram to waveform using librosa"""
  68. if hparams.signal_normalization:
  69. D = _denormalize(mel_spectrogram, hparams)
  70. else:
  71. D = mel_spectrogram
  72. S = _mel_to_linear(_db_to_amp(D + hparams.ref_level_db), hparams) # Convert back to linear
  73. if hparams.use_lws:
  74. processor = _lws_processor(hparams)
  75. D = processor.run_lws(S.astype(np.float64).T ** hparams.power)
  76. y = processor.istft(D).astype(np.float32)
  77. return inv_preemphasis(y, hparams.preemphasis, hparams.preemphasize)
  78. else:
  79. return inv_preemphasis(_griffin_lim(S ** hparams.power, hparams), hparams.preemphasis, hparams.preemphasize)
  80. def _lws_processor(hparams):
  81. import lws
  82. return lws.lws(hparams.n_fft, get_hop_size(hparams), fftsize=hparams.win_size, mode="speech")
  83. def _griffin_lim(S, hparams):
  84. """librosa implementation of Griffin-Lim
  85. Based on https://github.com/librosa/librosa/issues/434
  86. """
  87. angles = np.exp(2j * np.pi * np.random.rand(*S.shape))
  88. S_complex = np.abs(S).astype(np.complex)
  89. y = _istft(S_complex * angles, hparams)
  90. for i in range(hparams.griffin_lim_iters):
  91. angles = np.exp(1j * np.angle(_stft(y, hparams)))
  92. y = _istft(S_complex * angles, hparams)
  93. return y
  94. def _stft(y, hparams):
  95. if hparams.use_lws:
  96. return _lws_processor(hparams).stft(y).T
  97. else:
  98. return librosa.stft(y=y, n_fft=hparams.n_fft, hop_length=get_hop_size(hparams), win_length=hparams.win_size)
  99. def _istft(y, hparams):
  100. return librosa.istft(y, hop_length=get_hop_size(hparams), win_length=hparams.win_size)
  101. ##########################################################
  102. #Those are only correct when using lws!!! (This was messing with Wavenet quality for a long time!)
  103. def num_frames(length, fsize, fshift):
  104. """Compute number of time frames of spectrogram
  105. """
  106. pad = (fsize - fshift)
  107. if length % fshift == 0:
  108. M = (length + pad * 2 - fsize) // fshift + 1
  109. else:
  110. M = (length + pad * 2 - fsize) // fshift + 2
  111. return M
  112. def pad_lr(x, fsize, fshift):
  113. """Compute left and right padding
  114. """
  115. M = num_frames(len(x), fsize, fshift)
  116. pad = (fsize - fshift)
  117. T = len(x) + 2 * pad
  118. r = (M - 1) * fshift + fsize - T
  119. return pad, pad + r
  120. ##########################################################
  121. #Librosa correct padding
  122. def librosa_pad_lr(x, fsize, fshift):
  123. return 0, (x.shape[0] // fshift + 1) * fshift - x.shape[0]
  124. # Conversions
  125. _mel_basis = None
  126. _inv_mel_basis = None
  127. def _linear_to_mel(spectogram, hparams):
  128. global _mel_basis
  129. if _mel_basis is None:
  130. _mel_basis = _build_mel_basis(hparams)
  131. return np.dot(_mel_basis, spectogram)
  132. def _mel_to_linear(mel_spectrogram, hparams):
  133. global _inv_mel_basis
  134. if _inv_mel_basis is None:
  135. _inv_mel_basis = np.linalg.pinv(_build_mel_basis(hparams))
  136. return np.maximum(1e-10, np.dot(_inv_mel_basis, mel_spectrogram))
  137. def _build_mel_basis(hparams):
  138. assert hparams.fmax <= hparams.sample_rate // 2
  139. return librosa.filters.mel(hparams.sample_rate, hparams.n_fft, n_mels=hparams.num_mels,
  140. fmin=hparams.fmin, fmax=hparams.fmax)
  141. def _amp_to_db(x, hparams):
  142. min_level = np.exp(hparams.min_level_db / 20 * np.log(10))
  143. return 20 * np.log10(np.maximum(min_level, x))
  144. def _db_to_amp(x):
  145. return np.power(10.0, (x) * 0.05)
  146. def _normalize(S, hparams):
  147. if hparams.allow_clipping_in_normalization:
  148. if hparams.symmetric_mels:
  149. return np.clip((2 * hparams.max_abs_value) * ((S - hparams.min_level_db) / (-hparams.min_level_db)) - hparams.max_abs_value,
  150. -hparams.max_abs_value, hparams.max_abs_value)
  151. else:
  152. return np.clip(hparams.max_abs_value * ((S - hparams.min_level_db) / (-hparams.min_level_db)), 0, hparams.max_abs_value)
  153. assert S.max() <= 0 and S.min() - hparams.min_level_db >= 0
  154. if hparams.symmetric_mels:
  155. return (2 * hparams.max_abs_value) * ((S - hparams.min_level_db) / (-hparams.min_level_db)) - hparams.max_abs_value
  156. else:
  157. return hparams.max_abs_value * ((S - hparams.min_level_db) / (-hparams.min_level_db))
  158. def _denormalize(D, hparams):
  159. if hparams.allow_clipping_in_normalization:
  160. if hparams.symmetric_mels:
  161. return (((np.clip(D, -hparams.max_abs_value,
  162. hparams.max_abs_value) + hparams.max_abs_value) * -hparams.min_level_db / (2 * hparams.max_abs_value))
  163. + hparams.min_level_db)
  164. else:
  165. return ((np.clip(D, 0, hparams.max_abs_value) * -hparams.min_level_db / hparams.max_abs_value) + hparams.min_level_db)
  166. if hparams.symmetric_mels:
  167. return (((D + hparams.max_abs_value) * -hparams.min_level_db / (2 * hparams.max_abs_value)) + hparams.min_level_db)
  168. else:
  169. return ((D * -hparams.min_level_db / hparams.max_abs_value) + hparams.min_level_db)