Python实现中英文文本朗读的三种常用方法
作者:五步晦暝
本文介绍了Python实现中英文文本朗读的三种常用方法,1,pyttsx3:基于系统语音引擎,无需联网,可调节语速和音量,但语音较机械;2,gTTS:利用Google API生成高质量语音,需联网并生成临时文件;3, edge-tts:采用微软Azure,需要的朋友可以参考下
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中英文文本朗读的资料请关注脚本之家其它相关文章!
