TTS 之 PYTHON库 pyttsx3

pyttsx3是Python中一款轻量级、跨平台的离线文本转语音(TTS)库,可实现文本朗读、语音参数调控、语音文件保存等功能:

一、基本功能

1. pyttsx3初始化 init

复制代码
```python
import pyttsx3
engine = pyttsx3.init()
engine.say("pyttsx3 初始化!")
engine.runAndWait()
engine.stop()
```

2. 基础功能使用

基本文本朗读:

初始化语音引擎后,通过say()方法添加待朗读文本,再用runAndWait()触发语音播放,该方法会阻塞线程直至播放结束,

python 复制代码
    import pyttsx3
    engine = pyttsx3.init()
    text = "Hello, welcome to the world of Python and pyttsx3!"
    engine.say(text)
    engine.runAndWait()
    engine.stop()

语音速率调整:

通过getProperty('rate')获取当前语速(默认有固定值),再用setProperty('rate', value)设置新语速,取值范围通常为0-500,数值越大语速越快:

python 复制代码
	import pyttsx3
	engine = pyttsx3.init()
	rate = engine.getProperty('rate')
	print(f"当前语音速率: {rate}")
	engine.setProperty('rate', 500)
	engine.say("你好 tts.")
	engine.runAndWait()
	engine.stop()

语音音量控制:

借助getProperty('volume')获取当前音量,通过setProperty('volume', value)调节音量,取值范围为0.0(静音)-1.0(最大音量)。

python 复制代码
import pyttsx3
engine = pyttsx3.init()
volume = engine.getProperty('volume')
print(f"当前音量: {volume}")
engine.setProperty('volume', 0.7)
engine.say("你好 tts.")
engine.runAndWait()
engine.stop()

语音类型选择:

getProperty('voices')获取系统可用语音列表,列表中每个语音对象包含ID、名称、性别等信息,再通过setProperty('voice', voice_id)切换语音类型,示例:

python 复制代码
import pyttsx3
engine = pyttsx3.init()
voices = engine.getProperty('voices')
for voice in voices:
    print(f"语音ID: {voice.id}, 语音名称: {voice.name}, 语音性别: {voice.gender}")
engine.setProperty('voice', voices[0].id)
engine.say("This is a test with a different voice.")
engine.runAndWait()
engine.stop()

保存语音到文件:

使用save_to_file(text, filename)将语音保存为指定格式文件(如MP3、WAV,格式取决于系统引擎),且需调用runAndWait()确保保存完成,示例:

python 复制代码
import pyttsx3
engine = pyttsx3.init()
text = "This is a test. The speech will be saved to a file."
engine.save_to_file(text, 'output.mp3')
engine.runAndWait()
engine.stop()
相关推荐
ikun_文2 小时前
Django框架路由Router的使用
python·pycharm·django
IvanCodes2 小时前
Python 基础语法(二):字符串与常用操作
python
昭昭日月明2 小时前
LangChain 生态:从链到代理,开发者需要掌握的三大核心
python·langchain·agent
Csvn2 小时前
🐍 Day 8:面向对象编程
后端·python
程序员天天困2 小时前
向量检索不准怎么办:混合检索与 Rerank 重排序召回优化实战
后端·python·ai编程
alphaTao3 小时前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode
苏灿烤鱼4 小时前
当 AI Agent 遇见真实科学环境:深度拆解 Scientific Agent Skills,把"聊天机器人"变成"AI 科学家"
python·开源·agent
张文君4 小时前
ubuntu26.04坏道坏块分区隔离急速版260831-V0.12
linux·python
Interview Aid1124 小时前
TikTok OA 四题分享|半小时内 AC,题目基本都是实现题
java·开发语言·算法·面试·职场和发展
CoderIsArt11 小时前
C#中UI 线程与 Dispatcher
开发语言·ui·c#