file_utils.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. def read_lists(list_file):
  18. lists = []
  19. with open(list_file, 'r', encoding='utf8') as fin:
  20. for line in fin:
  21. lists.append(line.strip())
  22. return lists
  23. def read_json_lists(list_file):
  24. lists = read_lists(list_file)
  25. results = {}
  26. for fn in lists:
  27. with open(fn, 'r', encoding='utf8') as fin:
  28. results.update(json.load(fin))
  29. return results
  30. def load_wav(wav, target_sr):
  31. speech, sample_rate = torchaudio.load(wav)
  32. speech = speech.mean(dim=0, keepdim=True)
  33. if sample_rate != target_sr:
  34. assert sample_rate > target_sr, 'wav sample rate {} must be greater than {}'.format(sample_rate, target_sr)
  35. speech = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=target_sr)(speech)
  36. return speech