my_utils.py 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. import platform,os,traceback
  2. import ffmpeg
  3. import numpy as np
  4. def load_audio(file, sr):
  5. try:
  6. # https://github.com/openai/whisper/blob/main/whisper/audio.py#L26
  7. # This launches a subprocess to decode audio while down-mixing and resampling as necessary.
  8. # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.
  9. file = clean_path(file) # 防止小白拷路径头尾带了空格和"和回车
  10. if os.path.exists(file) == False:
  11. raise RuntimeError(
  12. "You input a wrong audio path that does not exists, please fix it!"
  13. )
  14. out, _ = (
  15. ffmpeg.input(file, threads=0)
  16. .output("-", format="f32le", acodec="pcm_f32le", ac=1, ar=sr)
  17. .run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True)
  18. )
  19. except Exception as e:
  20. traceback.print_exc()
  21. raise RuntimeError(f"Failed to load audio: {e}")
  22. return np.frombuffer(out, np.float32).flatten()
  23. def clean_path(path_str):
  24. if platform.system() == 'Windows':
  25. path_str = path_str.replace('/', '\\')
  26. return path_str.strip(" ").strip('"').strip("\n").strip('"').strip(" ")