To create a simple HTML5-Bootstrap5-Python3 text-to-speech (TTS) app using espeak on Ubuntu Linux that saves the audio file to your home directory and allows you to select from all possible voices, you can follow the steps below. This solution requires Flask, a Python micro web framework, to run a local server, and espeak installed on your system.
Step 1: Install Flask and espeak
pip3 install Flask
sudo apt-get install espeak
Step 2: Create the Flask application
Create a new directory for your project and inside that directory, create a Python file (e.g., app.py) and paste the following code:
from flask import Flask, render_template, request, send_file
import subprocess
import os
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def index():
voices = get_espeak_voices()
if request.method == "POST":
text = request.form.get("text")
voice = request.form.get("voice")
speak(text, voice)
return send_file(os.path.expanduser("~/output_tts.wav"), as_attachment=True)
return render_template("index.html", voices=voices)
def get_espeak_voices():
result = subprocess.run(["espeak", "--voices"], capture_output=True, text=True)
lines = result.stdout.split("\n")
voices = [line.split()[1] for line in lines[1:-1]] # Extracting voice codes
return voices
def speak(text, voice):
output_file = os.path.expanduser("~/output_tts.wav")
subprocess.run(["espeak", "-v", voice, text, "--stdout", f"> {output_file}"], shell=True)
if __name__ == "__main__":
app.run(debug=True)
Step 3: Create the HTML template
Inside your project directory, create a folder named templates, and inside this folder, create an HTML file named index.html. Paste the following code:
<!doctype html>
<html lang="en">
<head>
<title>TTS App</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Text-to-Speech Converter</h1>
<form method="POST">
<div class="mb-3">
<label for="voiceSelect" class="form-label">Select a Voice</label>
<select class="form-select" id="voiceSelect" name="voice">
{% for voice in voices %}
<option value="{{ voice }}">{{ voice }}</option>
{% endfor %}
</select>
</div>
<div class="mb-3">
<label for="textInput" class="form-label">Enter Text</label>
<textarea class="form-control" id="textInput" name="text" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">Speak & Download</button>
</form>
</div>
</body>
</html>
Step 4: Running the App
Navigate to your project directory in a terminal and run:
export FLASK_APP=app.py
flask run
Visit http://127.0.0.1:5000/ in your browser. You should see the web page with a dropdown for voice selection and a textarea for input text. Once you submit, espeak generates the speech, and the WAV file is automatically downloaded.
Note: This code is basic and intended for educational and prototyping purposes. For production, consider adding validation, using AJAX for asynchronous requests, and improving security measures.