import os import subprocess import tempfile from pathlib import Path import pyttsx3 def text_to_mp3(text: str, mp3_path: str) -> None: if not text: raise RuntimeError("텍스트가 비어 있습니다.") mp3_target = Path(mp3_path) mp3_target.parent.mkdir(parents=True, exist_ok=True) engine = pyttsx3.init() wav_fd, wav_path = tempfile.mkstemp(suffix=".wav") os.close(wav_fd) try: # pyttsx3로 wav 생성 후 ffmpeg로 mp3 변환 engine.save_to_file(text, wav_path) engine.runAndWait() subprocess.run( ["ffmpeg", "-y", "-i", wav_path, str(mp3_target)], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) if not mp3_target.exists(): raise RuntimeError("mp3 파일 생성에 실패했습니다.") except subprocess.CalledProcessError as exc: raise RuntimeError("ffmpeg 변환에 실패했습니다.") from exc except OSError as exc: raise RuntimeError("파일 생성 권한 또는 경로 오류입니다.") from exc finally: try: os.remove(wav_path) except OSError: pass