Python 中实现文本朗读的常用方法(支持中文/英文):


方法 1:使用 pyttsx3(推荐)

特点

  • 无需联网,基于系统内置语音引擎(Windows 自带 SAPI,Linux/macOS 需安装 espeakfestival)。
  • 可调节语速、音量,切换语音性别。

安装

pip install pyttsx3

基础示例

import pyttsx3

engine = pyttsx3.init()  # 初始化引擎

# 设置语速(默认 200,范围 0-500)
engine.setProperty('rate', 150)

# 设置音量(0.0~1.0)
engine.setProperty('volume', 0.8)

# 获取系统可用语音列表(切换男/女声)
voices = engine.getProperty('voices')
for voice in voices:
    print("Voice:", voice.name, voice.languages)

# 选择一个中文语音(需系统支持,如Windows中文语音包)
# engine.setProperty('voice', voices[1].id)  # 按索引切换

# 朗读文本
engine.say("你好,欢迎使用Python朗读功能。Hello, this is a TTS demo.")
engine.runAndWait()  # 阻塞直到朗读完成

方法 2:使用 gTTS + 播放库(需联网)

特点

  • 基于 Google 文本转语音 API,生成语音文件后播放。
  • 语音质量更自然,但依赖网络。

安装

pip install gtts playsound  # playsound 用于播放音频

示例

from gtts import gTTS
import os
from playsound import playsound

text = "你好,这是通过Google TTS生成的语音。"
tts = gTTS(text=text, lang='zh-cn')  # 中文:zh-cn,英文:en

# 保存为临时文件
tts.save("temp.mp3")
playsound("temp.mp3")  # 播放音频
os.remove("temp.mp3")  # 删除临时文件

方法 3:使用 edge-tts(微软 Edge 语音)

特点

  • 支持微软 Azure 的高质量语音(需安装 edge-tts 和播放库)。

安装

pip install edge-tts pygame  # pygame 用于播放音频

示例

import asyncio
from edge_tts import Communicate
import pygame

async def text_to_speech():
    text = "欢迎使用微软语音合成服务。"
    communicate = Communicate(text, "zh-CN-XiaoxiaoNeural")  # 中文女声
    await communicate.save("output.mp3")  # 保存文件
    
    # 播放音频
    pygame.mixer.init()
    pygame.mixer.music.load("output.mp3")
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        continue

asyncio.run(text_to_speech())

方法对比

方法优点缺点
pyttsx3无需联网,可调节参数语音机械感强,依赖系统语音包
gTTS语音自然,支持多语言需要联网,生成文件占用存储
edge-tts高质量微软语音,支持多种声线安装较复杂,依赖异步代码

常见问题解决

  1. pyttsx3 无声音(Linux/macOS)

    • 安装语音引擎:
      # Ubuntu/Debian
      sudo apt install espeak
      
      # macOS
      brew install espeak
      
  2. 中文朗读不生效

    • Windows:确保系统安装了中文语音包(设置 → 时间和语言 → 语音)。
    • 检查语音列表是否存在中文语音:
      engine = pyttsx3.init()
      voices = engine.getProperty('voices')
      for voice in voices:
          print(voice.name, voice.languages)
      
  3. gTTS 生成文件无法播放

    • 安装 ffmpeg 解码器:
      # Ubuntu/Debian
      sudo apt install ffmpeg
      
      # macOS
      brew install ffmpeg
      

根据需求选择合适的方法,如本地离线快速使用选 pyttsx3,追求语音质量选 gTTSedge-tts

Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐