63 lines
1.6 KiB
Markdown
63 lines
1.6 KiB
Markdown
|
|
# python 文字转语音
|
|||
|
|
|
|||
|
|
> 原文: [https://pythonbasics.org/text-to-speech/](https://pythonbasics.org/text-to-speech/)
|
|||
|
|
|
|||
|
|
文字转语音(TTS)是将书面文字转换为语音的方式。您可以使用 python 创建 TTS 程序。 语音的质量取决于您的语音引擎。
|
|||
|
|
|
|||
|
|
在本文中,您将学习如何创建自己的 TTS 程序。
|
|||
|
|
|
|||
|
|
|
|||
|
|
|
|||
|
|
## python 中的文字转语音
|
|||
|
|
|
|||
|
|
### espeak 示例
|
|||
|
|
|
|||
|
|
程序“espeak”是一个简单的语音合成器,可以将书面文本转换为语音。 espeak 程序听起来确实有点机器人化,但是它足够简单,可以构建一个基本程序。
|
|||
|
|
|
|||
|
|
```py
|
|||
|
|
import subprocess
|
|||
|
|
|
|||
|
|
def execute_unix(inputcommand):
|
|||
|
|
p = subprocess.Popen(inputcommand, stdout=subprocess.PIPE, shell=True)
|
|||
|
|
(output, err) = p.communicate()
|
|||
|
|
return output
|
|||
|
|
|
|||
|
|
a = "Say something in natural language."
|
|||
|
|
|
|||
|
|
# create wav file
|
|||
|
|
# w = 'espeak -w temp.wav "%s" 2>>/dev/null' % a
|
|||
|
|
# execute_unix(w)
|
|||
|
|
|
|||
|
|
# tts using espeak
|
|||
|
|
c = 'espeak -ven+f3 -k5 -s150 --punct="<characters>" "%s" 2>>/dev/null' % a
|
|||
|
|
execute_unix(c)
|
|||
|
|
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
### TTS 与 Google
|
|||
|
|
|
|||
|
|
Google 听起来很自然。 您可以将其 TTS 引擎与以下代码一起使用。
|
|||
|
|
对于此程序,您需要安装模块 gTTS 以及程序 mpg123。
|
|||
|
|
|
|||
|
|
```py
|
|||
|
|
# need gTTS and mpg123
|
|||
|
|
# pip install gTTS
|
|||
|
|
# apt install mpg123
|
|||
|
|
|
|||
|
|
from gtts import gTTS
|
|||
|
|
import os
|
|||
|
|
|
|||
|
|
# define variables
|
|||
|
|
s = "escape with plane"
|
|||
|
|
file = "file.mp3"
|
|||
|
|
|
|||
|
|
# initialize tts, create mp3 and play
|
|||
|
|
tts = gTTS(s, 'en')
|
|||
|
|
tts.save(file)
|
|||
|
|
os.system("mpg123 " + file)
|
|||
|
|
|
|||
|
|
```
|
|||
|
|
|
|||
|
|
这将输出语音/ mp3 文件。
|
|||
|
|
|
|||
|
|
[下载音频示例](https://social.pythonbasics.org/download-audio-examples/)
|