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()
相关推荐
Csvn16 小时前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
Wenweno0o16 小时前
0基础Go语言Eino框架智能体实战-chatModel
开发语言·后端·golang
chenjingming66616 小时前
jmeter线程组设置以及串行和并行设置
java·开发语言·jmeter
cch891816 小时前
Python主流框架全解析
开发语言·python
不爱吃炸鸡柳16 小时前
C++ STL list 超详细解析:从接口使用到模拟实现
开发语言·c++·list
十五年专注C++开发16 小时前
RTTR: 一款MIT 协议开源的 C++ 运行时反射库
开发语言·c++·反射
Momentary_SixthSense16 小时前
设计模式之工厂模式
java·开发语言·设计模式
sg_knight16 小时前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财17 小时前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
‎ദ്ദിᵔ.˛.ᵔ₎17 小时前
STL 栈 队列
开发语言·c++