pyttsx3 初识

一、pyttsx3 概述

pyttsx3是Python中的文本到语音转换库。与其他库不同,它可以脱机工作,并且与Python 2和3兼容。

二、安装

pip install pyttsx3

三、简单示例

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import pyttsx3
""" 语音播放 Hello World """
pyttsx3.speak("Hello World!")

或者

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import pyttsx3
""" 语音播放 Hello World """
engine = pyttsx3.init()
engine.say("Hello World!")
engine.runAndWait()

备注:其实 pyttsx3.speak 内部实现就是第二端代码

四、进阶示例

#!/usr/bin/env python
# -*- coding:utf-8 -*-

engine = pyttsx3.init() # object creation
""" 把语音存储到文件 """
engine.save_to_file("Hello World!!!",'~/abc.mp3')

"""更改速率"""
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 = 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

"""更改声音"""
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()

五、常见错误

1、OSError: libespeak.so.1: cannot open shared object file: No such file or directory
File "/usr/python/lib/python3.7/site-packages/pyttsx3/drivers/espeak.py", line 9, in <module>
    from . import _espeak, toUtf8, fromUtf8
  File "/usr/python/lib/python3.7/site-packages/pyttsx3/drivers/_espeak.py", line 18, in <module>
    dll = cdll.LoadLibrary('libespeak.so.1')
  File "/usr/python/lib/python3.7/ctypes/__init__.py", line 434, in LoadLibrary
    return self._dlltype(name)
  File "/usr/python/lib/python3.7/ctypes/__init__.py", line 356, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: libespeak.so.1: cannot open shared object file: No such file or directory

解决方法: yum -y install espeak

2、espeak centos 中文问题
git clone https://github.com/harry0731/espeak.git
cd espeak/dictsource/
espeak --compile=zh
3、sh: ffmpeg: 未找到命令
#安装EPEL Release
yum install -y epel-release rpm

#如果出现缺少Code提示,就执行此条命令
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7 

#导入一个Code
rpm --import http://li.nux.ro/download/nux/RPM-GPG-KEY-nux.ro 

#安装nux-dextop 源
rpm -Uvh http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-1.el7.nux.noarch.rpm
 
#查看repo源是否安装成功
yum repolist 

#安装ffmpeg
yum -y install ffmpeg

#验证
ffmpeg -version

六、官方文档

详细文档请查看官方文档