my_utils.py 870 B

123456789101112131415161718192021
  1. import ffmpeg
  2. import numpy as np
  3. def load_audio(file, sr):
  4. try:
  5. # https://github.com/openai/whisper/blob/main/whisper/audio.py#L26
  6. # This launches a subprocess to decode audio while down-mixing and resampling as necessary.
  7. # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.
  8. file = (
  9. file.strip(" ").strip('"').strip("\n").strip('"').strip(" ")
  10. ) # 防止小白拷路径头尾带了空格和"和回车
  11. out, _ = (
  12. ffmpeg.input(file, threads=0)
  13. .output("-", format="f32le", acodec="pcm_f32le", ac=1, ar=sr)
  14. .run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True)
  15. )
  16. except Exception as e:
  17. raise RuntimeError(f"Failed to load audio: {e}")
  18. return np.frombuffer(out, np.float32).flatten()