file_utils.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # Copyright (c) 2021 Mobvoi Inc. (authors: Binbin Zhang)
  2. # 2024 Alibaba Inc (authors: Xiang Lyu)
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import json
  16. import torchaudio
  17. import logging
  18. logging.getLogger('matplotlib').setLevel(logging.WARNING)
  19. logging.basicConfig(level=logging.DEBUG,
  20. format='%(asctime)s %(levelname)s %(message)s')
  21. def read_lists(list_file):
  22. lists = []
  23. with open(list_file, 'r', encoding='utf8') as fin:
  24. for line in fin:
  25. lists.append(line.strip())
  26. return lists
  27. def read_json_lists(list_file):
  28. lists = read_lists(list_file)
  29. results = {}
  30. for fn in lists:
  31. with open(fn, 'r', encoding='utf8') as fin:
  32. results.update(json.load(fin))
  33. return results
  34. def load_wav(wav, target_sr):
  35. speech, sample_rate = torchaudio.load(wav)
  36. speech = speech.mean(dim=0, keepdim=True)
  37. if sample_rate != target_sr:
  38. assert sample_rate > target_sr, 'wav sample rate {} must be greater than {}'.format(sample_rate, target_sr)
  39. speech = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=target_sr)(speech)
  40. return speech
  41. def speed_change(waveform, sample_rate, speed_factor: str):
  42. effects = [
  43. ["tempo", speed_factor], # speed_factor
  44. ["rate", f"{sample_rate}"]
  45. ]
  46. augmented_waveform, new_sample_rate = torchaudio.sox_effects.apply_effects_tensor(
  47. waveform,
  48. sample_rate,
  49. effects
  50. )
  51. return augmented_waveform, new_sample_rate