Would you like to convert your text documents or articles into speech that you can listen to wherever you want? This Python script makes it easy for you. It takes text input from a file and generates an audio output in mp3 or .wav format. Then you can put your feet up and listen to it while driving, working out, or just chilling.
We will utilize pyttsx3, an offline text-to-speech conversion library. You do not have to do anything but just mention the name of your text file and the name the audio file will be stored as. The script does the rest!
It is an excellent tool for readers who listen when they read, or if you want to generate audio versions of your files. Try and see your content in a fresh manner!
Text-to-Speech Converter Python Script
Here’s a Python script for a Text-to-Speech Converter that reads text from a file, converts it to speech, and saves it as an audio file using the pyttsx3 library:
import pyttsx3
import os
def text_to_speech(file_path, output_audio_file):
# Initialize the text-to-speech engine
engine = pyttsx3.init()
try:
# Check if the file exists
if not os.path.exists(file_path):
print(f"File not found: {file_path}")
return
# Read the content of the file
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read()
if not text.strip():
print("The file is empty.")
return
# Convert text to speech
print("Converting text to speech...")
engine.save_to_file(text, output_audio_file)
# Wait for the conversion to complete
engine.runAndWait()
print(f"Audio file saved as: {output_audio_file}")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
# Input text file path
text_file_path = input("Enter the path to the text file: ").strip()
# Output audio file path
output_audio_file_path = input("Enter the path to save the audio file (e.g., output.mp3): ").strip()
# Convert text to speech
text_to_speech(text_file_path, output_audio_file_path)
How to Use?
These steps will help you to use this script:
- Fistly install the Python pyttsx3 module, if not already installed. You can also consider to create a separate Python virtual environment.
pip install pyttsx3
- Save the script as
text_to_speech.py
. - Run the script:
python text_to_speech.py
Provide the path to a text file and specify the desired name and location for the output audio file (e.g., output.mp3).
You can customize the speech properties (e.g., speed, volume, voice) by configuring the pyttsx3 engine settings.
The post Text-to-Speech Converter in Python: Turn Text into Audio Files appeared first on TecAdmin.
Source: Read More