To convert text to MP3 in Python, you can use the gTTS (Google Text-to-Speech) library. This library allows you to generate an MP3 file from a given text. Here’s an example code snippet.
In this code, we define the text_to_speech function that takes two parameters: filename (the name of the input text file) and output_filename (the name of the output MP3 file). The function reads the contents of the input file using open() and read(), and replaces any newline characters (‘\n’) with spaces to ensure a continuous text.
Then, it proceeds to generate the MP3 file using gTTS, just like before, and saves it with the provided output filename.
To use this code, make sure you have a text file (e.g., input.txt) containing the text you want to convert. Then, specify the input and output filenames when calling the text_to_speech function.
For example, if your input file is input.txt and you want to save the MP3 as output.mp3, you would call the function as follows.
pip install gtts pip install pyttsx3
The gTTS library uses the default voice available for the specified language, which is usually a female voice. If you specifically want a male voice or a different voice quality, you might need to use a different library or service. One option is the pyttsx3 library, which supports multiple voices. Here’s an example of how you can use pyttsx3 to convert text to speech with a male voice.
Note that the gTTS library relies on an internet connection to access the Google Text-to-Speech API and generate the audio file.
Complete a small survey and download the script
[button-green url=”https://optilinklock.com/1420598″ target=”_self” position=”center”]Download Script[/button-green]
Visit Best SEO Website: https://websiteseo.me