如何将 pyttsx3 结果保存为 MP3 或 WAV 文件?
在本文中,我们将看到如何生成pyttsx3结果并将其保存为 mp3 和 wav 文件。 Pyttsx3是一个提供文本到语音 API 的Python模块。我们可以使用此 API 将文本转换为语音。
环境设置:
要使用 pyttsx3,我们必须先安装espeak和ffmpeg 。
sudo apt update
sudo apt install espeak
sudo apt install ffmpeg
另外,我们需要安装最新版本的pyttsx3
python3 -m pip install pyttsx3
我们可以通过导入模块来确认安装。
import pyttsx3
如果上面的语句运行没有错误,则环境设置成功。
使用 Pyttsx3
- 首先,我们必须初始化pyttsx3引擎。 init()方法为我们做到了这一点。
- 接下来,我们需要使用要转换为音频的文本创建一个字符串。
- say()方法将字符串作为参数。它将设置它必须说话的字符串。
- 由于语音在机器的扬声器上播放需要一段时间,我们需要等待该过程完成。因此,我们需要调用runAndWait()方法,以便让解释器停止执行直到那时。
- 以下是上述步骤的代码:
Python3
# Import the required module
import pyttsx3
# Create a string
string = "Lorem Ipsum is simply dummy text " \
+ "of the prting and typesetting industry."
# Initialize the Pyttsx3 engine
engine = pyttsx3.init()
# Command it to speak the given string
engine.say(string)
# Wait until above command is not finished.
engine.runAndWait()
Python3
# Import the required module
import pyttsx3
# Create a string
string = "Lorem Ipsum is simply dummy text " \
+ "of the prting and typesetting industry."
# Initialize the Pyttsx3 engine
engine = pyttsx3.init()
# We can use file extension as mp3 and wav, both will work
engine.save_to_file(string, 'speech.mp3')
# Wait until above command is not finished.
engine.runAndWait()
输出:
将产生的声音保存在文件中
- 请注意,我们的系统中需要有ffmpeg 。因此,请确保环境设置正确完成。
- Pyttsx3带有一个save_to_file()方法,该方法将要朗读的文本和文件路径作为参数。
- 此方法将给定的文件保存在路径中。但是,该模块处于开发状态,因此在某些操作系统中,音量和速率选项可能无法正常工作。
- 我们必须将库更新到最新版本。使用以下命令安装模块:
sudo apt install git
python3 -m pip install git+https://github.com/nateshmbhat/pyttsx3
- 这将直接安装可用的最新版本。
- 下面是执行相同操作的代码:
蟒蛇3
# Import the required module
import pyttsx3
# Create a string
string = "Lorem Ipsum is simply dummy text " \
+ "of the prting and typesetting industry."
# Initialize the Pyttsx3 engine
engine = pyttsx3.init()
# We can use file extension as mp3 and wav, both will work
engine.save_to_file(string, 'speech.mp3')
# Wait until above command is not finished.
engine.runAndWait()
输出: