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()
相关推荐
明月醉窗台3 分钟前
qt使用笔记六之 Qt Creator、Qt Widgets、Qt Quick 详细解析
开发语言·笔记·qt
wangjialelele6 分钟前
平衡二叉搜索树:AVL树和红黑树
java·c语言·开发语言·数据结构·c++·算法·深度优先
深蓝电商API7 分钟前
住宅代理与数据中心代理在爬虫中的选择
爬虫·python
lili-felicity14 分钟前
CANN性能调优与实战问题排查:从基础优化到排障工具落地
开发语言·人工智能
独自破碎E16 分钟前
【BISHI15】小红的夹吃棋
android·java·开发语言
进阶小白猿28 分钟前
Java技术八股学习Day33
java·开发语言·学习
哈__1 小时前
CANN加速语音识别ASR推理:声学模型与语言模型融合优化
人工智能·语言模型·语音识别
历程里程碑1 小时前
普通数组----合并区间
java·数据结构·python·算法·leetcode·职场和发展·tornado
weixin_395448911 小时前
mult_yolov5_post_copy.c_cursor_0205
c语言·python·yolo
执风挽^1 小时前
Python基础编程题2
开发语言·python·算法·visual studio code