📜  在Python中将文本转换为语音

📅  最后修改于: 2022-05-13 01:55:34.963000             🧑  作者: Mango

在Python中将文本转换为语音

在Python中有几个 API 可用于将文本转换为语音。此类 API 之一是 Google Text to Speech API,通常称为 gTTS API。 gTTS 是一个非常易于使用的工具,可以将输入的文本转换为可以保存为 mp3 文件的音频。

gTTS API 支持多种语言,包括英语、印地语、泰米尔语、法语、德语等等。语音可以以两种可用的音频速度中的任何一种来传递,快或慢。但是,在最新的更新中,无法更改生成的音频的声音。

安装

要安装 gTTS API,请打开终端并编写

pip install gTTS

这适用于任何平台。
现在我们都准备好编写一个将文本转换为语音的示例程序。

# Import the required module for text 
# to speech conversion
from gtts import gTTS
  
# This module is imported so that we can 
# play the converted audio
import os
  
# The text that you want to convert to audio
mytext = 'Welcome to geeksforgeeks!'
  
# Language in which you want to convert
language = 'en'
  
# Passing the text and language to the engine, 
# here we have marked slow=False. Which tells 
# the module that the converted audio should 
# have a high speed
myobj = gTTS(text=mytext, lang=language, slow=False)
  
# Saving the converted audio in a mp3 file named
# welcome 
myobj.save("welcome.mp3")
  
# Playing the converted file
os.system("mpg321 welcome.mp3")

输出

The output of the above program should be a 
voice saying, 'Welcome to geeksforgeeks!'