Edge-tts库一次支持多少个中文,语速支持设置吗?

2025-07-23 01:09:12 10 分享链接 开发笔记 python

文本长度限制

Edge TTS 对单次请求的文本长度有一定限制,具体限制如下:

  1. API 限制:每次请求最多支持 3000 个字符
  2. 实际使用建议:建议将长文本分段处理,每段不超过 2000 字符,以避免请求超时或失败

语速调节支持

Edge TTS 完全支持语速调节,通过 rate 参数可以设置语速,格式为 "+XX%""-XX%"

  • "+50%" 表示语速加快 50%
  • "-30%" 表示语速减慢 30%
  • "+0%" 表示默认语速

长文本分段处理示例

以下是一个支持长文本分段处理并可自定义语速的完整示例:

import asyncio
import edge_tts
from pathlib import Path

async def split_text_to_speech(
    text: str,
    output_dir: str = "output",
    voice: str = "zh-CN-YunxiNeural",
    rate: str = "+0%",
    volume: str = "+0%",
    chunk_size: int = 2000
) -> None:
    """
    将长文本分段并转换为语音
    
    Args:
        text: 待转换的长文本
        output_dir: 输出音频文件目录
        voice: 语音模型名称
        rate: 语速调整,如 "+50%" 或 "-30%"
        volume: 音量调整
        chunk_size: 每段文本的最大长度
    """
    # 创建输出目录
    Path(output_dir).mkdir(parents=True, exist_ok=True)
    
    # 按句子分段
    import re
    sentences = re.split(r'([。!?\.\!\?])', text)
    chunks = []
    current_chunk = ""
    
    for i in range(0, len(sentences), 2):
        if i < len(sentences) - 1:
            sentence = sentences[i] + sentences[i+1]
        else:
            sentence = sentences[i]
        
        if len(current_chunk) + len(sentence) > chunk_size:
            chunks.append(current_chunk)
            current_chunk = sentence
        else:
            current_chunk += sentence
    
    if current_chunk:
        chunks.append(current_chunk)
    
    # 分段生成语音
    tasks = []
    for i, chunk in enumerate(chunks):
        output_file = Path(output_dir) / f"part_{i+1}.mp3"
        communicate = edge_tts.Communicate(
            text=chunk,
            voice=voice,
            rate=rate,
            volume=volume
        )
        tasks.append(communicate.save(str(output_file)))
    
    # 并发执行
    await asyncio.gather(*tasks)
    print(f"语音合成完成,共生成 {len(chunks)} 个音频文件")

# 使用示例
if __name__ == "__main__":
    # 超长文本示例
    long_text = """
    这是一段超长的测试文本,用于演示Edge TTS的长文本处理能力。
    该库支持将文本分段处理,避免超出API限制。
    你可以调整chunk_size参数来控制每段的长度,建议值为1500-2000字符。
    
    语速调节功能允许你通过rate参数加快或减慢语音速度。
    例如:
    - rate="+50%" 会使语速提高50%
    - rate="-30%" 会使语速降低30%
    
    同时,你还可以调整音量(volume)、选择不同的语音模型(voice)。
    Edge TTS支持多种中文语音,包括云希、晓辰、晓晓等。
    
    长文本处理时,建议按语义完整的句子进行分割,
    这样可以保证每段语音的连贯性和自然度。
    """
    
    asyncio.run(
        split_text_to_speech(
            text=long_text,
            output_dir="output_chunks",
            voice="zh-CN-YunxiNeural",
            rate="+0%",  # 默认语速
            chunk_size=1800
        )
    )

高级用法:合并分段音频

如果你需要将分段生成的音频合并为一个文件,可以使用 pydub 库:

from pydub import AudioSegment
import os

def merge_audio_files(input_dir: str, output_file: str = "merged_output.mp3") -> None:
    """合并多个音频文件为一个"""
    # 获取所有音频文件
    audio_files = sorted(
        [f for f in os.listdir(input_dir) if f.endswith('.mp3')],
        key=lambda x: int(x.split('_')[1].split('.')[0])
    )
    
    if not audio_files:
        print("没有找到音频文件")
        return
    
    # 合并音频
    combined = AudioSegment.empty()
    for file in audio_files:
        audio = AudioSegment.from_mp3(os.path.join(input_dir, file))
        combined += audio
    
    # 保存合并后的文件
    combined.export(output_file, format="mp3")
    print(f"音频已合并并保存到 {output_file}")

# 使用示例
# merge_audio_files("output_chunks", "full_speech.mp3")

需要先安装 pydubffmpeg

pip install pydub
# 还需要安装ffmpeg: https://ffmpeg.org/download.html

语速和音量调整示例

# 语速加快50%
asyncio.run(
    text_to_speech(
        text="这段语音的语速加快了50%",
        output_file="faster_speech.mp3",
        rate="+50%"
    )
)

# 语速减慢30%,音量提高20%
asyncio.run(
    text_to_speech(
        text="这段语音的语速减慢了30%,音量提高了20%",
        output_file="slower_louder_speech.mp3",
        rate="-30%",
        volume="+20%"
    )
)

这些功能使 Edge TTS 能够灵活满足不同场景的需求,无论是有声读物、语音助手还是其他应用。

Edge-tts库一次支持多少个中文,语速支持设置吗?