python 中实现文本朗读的常用方法(支持中文/英文):
方法 1:使用pyttsx3(推荐)
特点:
- 无需联网,基于系统内置语音引擎(windows 自带 sapi,linux/macos 需安装
espeak或festival)。 - 可调节语速、音量,切换语音性别。
安装:
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,追求语音质量选 gtts 或 edge-tts。
以上就是python实现中英文文本朗读的三种常用方法的详细内容,更多关于python中英文文本朗读的资料请关注代码网其它相关文章!
发表评论