Open In App

How to save pyttsx3 results to MP3 or WAV file?

In this article, we will see how to generate and save pyttsx3 results as mp3 and wav file. Pyttsx3 is a python module that provides a Text to Speech API. We can use this API to convert the text into voice. 

Environment setup:

To use pyttsx3 we have to install espeak and ffmpeg first.



sudo apt update
sudo apt install espeak
sudo apt install ffmpeg

Additionally, we need to install the latest version of pyttsx3

python3 -m pip install pyttsx3

We can confirm the installation by importing the module.

import pyttsx3

If the above statement runs without error, the environment setup is successful.



Using Pyttsx3




# Import the required module
import pyttsx3
 
# Create a string
string = "Lorem Ipsum is simply dummy text " \
    + "of the printing 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()

Output:

Saving the produced sound in a file

sudo apt install git
python3 -m pip install git+https://github.com/nateshmbhat/pyttsx3




# Import the required module
import pyttsx3
 
# Create a string
string = "Lorem Ipsum is simply dummy text " \
    + "of the printing 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()

Output:


Article Tags :