python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python中英文文本朗读

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

作者:五步晦暝

本文介绍了Python实现中英文文本朗读的三种常用方法,1,pyttsx3:基于系统语音引擎,无需联网,可调节语速和音量,但语音较机械;2,gTTS:利用Google API生成高质量语音,需联网并生成临时文件;3, edge-tts:采用微软Azure,需要的朋友可以参考下

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

方法 1:使用pyttsx3(推荐)

特点

安装

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+ 播放库(需联网)

特点

安装

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 语音)

特点

安装

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

中文朗读不生效

engine = pyttsx3.init()
voices = engine.getProperty('voices')
for voice in voices:
    print(voice.name, voice.languages)

gTTS 生成文件无法播放

# Ubuntu/Debian
sudo apt install ffmpeg
# macOS
brew install ffmpeg

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

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

您可能感兴趣的文章:
阅读全文