AdGame 发表于 3 天前

TTS生成语音Python源码


https://att.ijingyi.com/data/attachment/forum/202509/14/223618xf9wm9jjmxt7ccjt.jpg

# -*- coding: utf-8 -*-
"""
TTS 生成器 —— 读取 A.txt 内容生成 MP3
✅ 从 A.txt 读取正文
✅ 从 config.txt 读取配置(可选)
✅ 免注册、免Key、使用 edge-tts
✅ 自动生成 output 文件夹
✅ 错误处理 + 进度提示
"""

import asyncio
import edge_tts
import os
import sys
from pathlib import Path


# ========== 默认配置 ==========
DEFAULT_VOICE = "zh-CN-YunxiNeural"
DEFAULT_RATE = "-10%"
DEFAULT_PITCH = "+5Hz"
DEFAULT_VOLUME = "+0%"
DEFAULT_OUTPUT_FILE = "output.mp3"
OUTPUT_DIR = "output"
TEXT_FILE = "需要生成的文本.txt"


# ========== 读取 A.txt ==========
def read_text_file(filepath=TEXT_FILE):
    """读取 A.txt 中的文本内容"""
    if not os.path.exists(filepath):
      print(f"❌ 文本文件 {filepath} 不存在!")
      return None

    try:
      with open(filepath, "r", encoding="utf-8") as f:
            content = f.read().strip()
      if not content:
            print(f"❌ {filepath} 内容为空!")
            return None
      return content
    except Exception as e:
      print(f"❌ 读取 {filepath} 失败:{e}")
      return None


# ========== 读取 config.txt ==========
def read_config_file(config_path="config.txt"):
    """读取配置文件,返回参数字典"""
    config = {
      "output_file": DEFAULT_OUTPUT_FILE,
      "voice": DEFAULT_VOICE,
      "rate": DEFAULT_RATE,
      "pitch": DEFAULT_PITCH,
      "volume": DEFAULT_VOLUME,
    }

    if not os.path.exists(config_path):
      print(f"⚠️配置文件 {config_path} 不存在,使用默认参数")
      return config

    try:
      with open(config_path, "r", encoding="utf-8") as f:
            lines = f.readlines()

      for line in lines:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            if "=" in line:
                key, value = line.split("=", 1)
                key = key.strip()
                value = value.strip()
                if key in config:
                  config = value

      print("✅ 已加载配置文件")
      return config

    except Exception as e:
      print(f"⚠️读取配置文件失败,使用默认参数:{e}")
      return config


# ========== 语音合成函数 ==========
async def generate_audio(text, config):
    """根据文本和配置生成语音文件"""
    output_file = config["output_file"]
    voice = config["voice"]
    rate = config["rate"]
    pitch = config["pitch"]
    volume = config["volume"]

    # 确保输出目录存在
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    full_path = os.path.join(OUTPUT_DIR, output_file)

    print(f"\n



页: [1]
查看完整版本: TTS生成语音Python源码