把指定目录下所有txt文件,用Windows系统自带语音引擎(SAPI)转换为wav音频。
import os
import win32com.client
# ====== 配置区 ======
TXT_DIR = r"G:\test" # 你的txt目录
OUTPUT_DIR = r"G:\test" # 输出音频目录
VOICE_NAME = "Microsoft Huihui Desktop" # 可换成 powershell -Command "(New-Object -ComObject SAPI.SpVoice).GetVoices() | ForEach-Object { $_.GetDescription() }"
RATE = 0 # 语速(-10 ~ 10)
VOLUME = 100 # 音量(0 ~ 100)
# ===================
os.makedirs(OUTPUT_DIR, exist_ok=True)
speaker = win32com.client.Dispatch("SAPI.SpVoice")
speaker.Voice = [v for v in speaker.GetVoices() if VOICE_NAME in v.GetDescription()][0]
speaker.Rate = RATE
speaker.Volume = VOLUME
for file in os.listdir(TXT_DIR):
if file.lower().endswith(".txt"):
txt_path = os.path.join(TXT_DIR, file)
wav_path = os.path.join(OUTPUT_DIR, os.path.splitext(file)[0] + ".wav")
with open(txt_path, "r", encoding="utf-8") as f:
text = f.read().strip()
if not text:
print(f"⚠ 跳过空文件: {file}")
continue
print(f"🎤 正在生成: {file} → {wav_path}")
stream = win32com.client.Dispatch("SAPI.SpFileStream")
stream.Open(wav_path, 3, False)
speaker.AudioOutputStream = stream
speaker.Speak(text)
stream.Close()
print("✅ 全部转换完成!")
❤️ 转载文章请注明出处,谢谢!❤️