每日一包 - pyttsx3

690 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第21天,点击查看活动详情

介绍

pyttsx3是一个适用于Python2和Python3的文本转语音(TTS, text to sound)库,无需互联网即离线就可以工作,可以通过控制参数来控制声音、语速、音量等,还可以将生成的声音保存到文件中,使用起来非常方便。

当我们自己做一些小视频又不想自己配音的话,可以直接提供文稿由程序生成声音直接进行配音是不是很方便呐?

安装和使用

安装

pip install pyttsx3

如果安装过程中提示No module named win32com.clientNo module named win32No module named win32api等错误,就需要额外安装pypiwin32

使用

我们首先来看一下该模块的基本使用,即将文字转换成语音

import pyttsx3
​
engine = pyttsx3.init()  # 生成引擎对象
engine.say("hello world")  # 参数就是需要转换成语音的文字
engine.runAndWait()  # 女声文字哦~

我们也可以将生成的声音保存到文件中。

import pyttsx3
engine = pyttsx3.init()
engine.save_to_file('Hello World' , 'test.mp3')
engine.runAndWait()

也可以通过参数改变声音:

engine = pyttsx3.init()
voices = engine.getProperty('voices')
for voice in voices:
   engine.setProperty('voice', voice.id)
   engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()

通过参数改变语速:

engine = pyttsx3.init()
rate = engine.getProperty('rate')
engine.setProperty('rate', rate+50)
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()

通过参数改变音量:

engine = pyttsx3.init()
volume = engine.getProperty('volume')
engine.setProperty('volume', volume-0.25)
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()

关于上述改变声音、语速和音量我们可以结合使用:

import pyttsx3
engine = pyttsx3.init() # object creation""" RATE"""
rate = engine.getProperty('rate')   # getting details of current speaking rate
print (rate)                        #printing current voice rate
engine.setProperty('rate', 125)     # setting up new voice rate
​
​
"""VOLUME"""
volume = engine.getProperty('volume')   #getting to know current volume level (min=0 and max=1)
print (volume)                          #printing current volume level
engine.setProperty('volume',1.0)    # setting up volume level  between 0 and 1"""VOICE"""
voices = engine.getProperty('voices')       #getting details of current voice
#engine.setProperty('voice', voices[0].id)  #changing index, changes voices. o for male
engine.setProperty('voice', voices[1].id)   #changing index, changes voices. 1 for female
​
engine.say("Hello World!")
engine.say('My current speaking rate is ' + str(rate))
engine.runAndWait()
engine.stop()
​
"""Saving Voice to a file"""
# On linux make sure that 'espeak' and 'ffmpeg' are installed
engine.save_to_file('Hello World', 'test.mp3')
engine.runAndWait()

总结

本文只介绍了部分关于该模块的使用更多的关于该模块的使用比如如何指定语言,默认只能识别中文和英文,可以参考官方网站pypi.org/project/pyt…和官方文档pyttsx3.readthedocs.io/en/latest/