当前位置: 代码网 > it编程>前端脚本>Python > Python实现中英文文本朗读的三种常用方法

Python实现中英文文本朗读的三种常用方法

2026年04月01日 Python 我要评论
python 中实现文本朗读的常用方法(支持中文/英文):方法 1:使用pyttsx3(推荐)特点:无需联网,基于系统内置语音引擎(windows 自带 sapi,linux/macos 需安装 es

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高质量微软语音,支持多种声线安装较复杂,依赖异步代码

常见问题解决

pyttsx3 无声音(linux/macos)

  • 安装语音引擎:
# ubuntu/debian
sudo apt install espeak
# macos
brew install espeak

中文朗读不生效

  • windows:确保系统安装了中文语音包(设置 → 时间和语言 → 语音)。
  • 检查语音列表是否存在中文语音:
engine = pyttsx3.init()
voices = engine.getproperty('voices')
for voice in voices:
    print(voice.name, voice.languages)

gtts 生成文件无法播放

  • 安装 ffmpeg 解码器:
# ubuntu/debian
sudo apt install ffmpeg
# macos
brew install ffmpeg

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

以上就是python实现中英文文本朗读的三种常用方法的详细内容,更多关于python中英文文本朗读的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com