audio_extractor.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import subprocess
  2. from utils.logger_config import setup_logger
  3. logger = setup_logger(__name__)
  4. def extract_audio(video_path):
  5. """
  6. Extract audio from video file using ffmpeg
  7. Args:
  8. video_path: Path to input video file
  9. Returns:
  10. str: Path to extracted audio file (.wav)
  11. """
  12. try:
  13. # Generate output audio path by replacing video extension with .wav
  14. audio_path = video_path.rsplit('.', 1)[0] + '.wav'
  15. # ffmpeg command to extract audio
  16. command = [
  17. 'ffmpeg', '-y',
  18. '-i', video_path,
  19. '-vn', # Disable video
  20. '-acodec', 'pcm_s16le', # Set audio codec
  21. '-ar', '16000', # Set sample rate
  22. '-ac', '1', # Set to mono channel
  23. audio_path
  24. ]
  25. # Execute ffmpeg command
  26. result = subprocess.run(command, capture_output=True, text=True)
  27. if result.returncode != 0:
  28. logger.error(f"Audio extraction failed: {result.stderr}")
  29. raise RuntimeError("Failed to extract audio")
  30. # logger.info("音频文件提取成功!")
  31. return audio_path
  32. except Exception as e:
  33. logger.error(f"Error during audio extraction: {str(e)}")
  34. raise