Build an Audiobook Generator Using ElevenLabs API
Why Turn Text Into Audio? If you’ve ever wanted to turn a blog post, a technical guide, or a novel into an audiobook, you’ve probably run into two big hurdles: Finding a natural‑sounding voice – most TTS engines sou
Why Turn Text Into Audio?
If you’ve ever wanted to turn a blog post, a technical guide, or a novel into an audiobook, you’ve probably run into two big hurdles:
- Finding a natural‑sounding voice – most TTS engines sound robotic or monotone.
- Automating the workflow – stitching together chapters, handling punctuation, and keeping the audio file size reasonable can become a mini‑project in itself.
Enter ElevenLabs. Their API delivers high‑fidelity, human‑like speech with a handful of HTTP calls, and you can even clone your own voice if you have a few minutes of clean audio. In this post we’ll walk through a complete end‑to‑end audiobook generator in Python, from pulling raw text to producing a single MP3 file ready for distribution.
👉 Ready to try it? Grab your free API key at the official ElevenLabs link: https://try.elevenlabs.io/kr07zfuqn1bp
Overview of the Pipeline
Markdown/HTML → Clean Text → Chunking → TTS (ElevenLabs) → Concatenate → MP3
- Source – We’ll start with a plain‑text file (or any string).
- Cleaning – Strip out markdown, HTML tags, and fix punctuation so the TTS engine gets the right pauses.
- Chunking – ElevenLabs caps each request at ~5 KB of text, so we split the book into manageable pieces.
-
Synthesis – Call the
/v1/text-to-speech/{voice_id}endpoint for each chunk. -
Merging – Use
pydubto concatenate the returned audio buffers into one seamless file.
Prerequisites
| Tool | Reason |
|---|---|
| Python 3.9+ | Clean, easy to read, and has great HTTP libraries. |
requests |
Simple HTTP client for the API calls. |
pydub + ffmpeg
|
Handles audio concatenation and export to MP3. |
| ElevenLabs API key | Required for every request – get yours from the affiliate link above. |
Install the Python dependencies:
pip install requests pydub tqdm
# On macOS / Linux you also need ffmpeg:
# brew install ffmpeg # macOS
# sudo apt-get install ffmpeg # Ubuntu/Debian
Step 1 – Load and Clean the Text
import re
from pathlib import Path
def load_and_clean(file_path: str) -> str:
raw = Path(file_path).read_text(encoding="utf-8")
# Remove markdown headers, code fences, and HTML tags
clean = re.sub(r'(?m)^#.*$', '', raw) # headers
clean = re.sub(r'```
.*?
```', '', clean, flags=re.DOTALL) # code blocks
clean = re.sub(r'<[^>]+>', '', clean) # HTML tags
# Collapse multiple newlines into a single one
clean = re.sub(r'\n{2,}', '\n', clean).strip()
return clean
You can feed any .txt, .md, or even a scraped HTML article into this function. The goal is to give the TTS engine a clean, punctuation‑rich string so it can pause naturally.
Step 2 – Chunk the Text
ElevenLabs recommends keeping each request under ~5 KB of UTF‑8 text. A safe way is to split on sentence boundaries while respecting a max‑character limit.
import nltk
nltk.download('punkt')
from nltk.tokenize import sent_tokenize
MAX_CHARS = 4500 # a bit under the 5 KB limit for safety
def chunk_text(text: str):
sentences = sent_tokenize(text)
chunks = []
current = ""
for s in sentences:
# If adding the next sentence would exceed the limit, start a new chunk
if len(current) + len(s) + 1 > MAX_CHARS:
chunks.append(current.strip())
current = s
else:
current += " " + s
if current:
chunks.append(current.strip())
return chunks
Now chunks is a list where each element can be sent to the ElevenLabs API.
Step 3 – Call the ElevenLabs TTS Endpoint
The API expects a JSON payload with the text and optional voice settings. Below is a minimal wrapper that returns raw audio bytes.
import requests
from tqdm import tqdm
ELEVEN_API_KEY = "YOUR_ELEVENLABS_API_KEY"
VOICE_ID = "21m00Tcm4TlvDq8ikWAM" # default “Rachel” voice – replace with your own
def synthesize(chunk: str) -> bytes:
url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}"
headers = {
"xi-api-key": ELEVEN_API_KEY,
"Content-Type": "application/json"
}
payload = {
"text": chunk,
"model_id": "eleven_monolingual_v1",
"voice_settings": {
"stability": 0.75,
"similarity_boost": 0.85
}
}
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
return response.content # MP3 bytes
If you have a custom voice cloned through ElevenLabs, replace VOICE_ID with the ID you received after uploading your samples. The same endpoint works for both stock and custom voices.
Step 4 – Stitch the Audio Together
from pydub import AudioSegment
import io
def build_audiobook(chunks):
combined = AudioSegment.empty()
for i, chunk in enumerate(tqdm(chunks, desc="Synthesizing")):
audio_bytes = synthesize(chunk)
segment = AudioSegment.from_file(io.BytesIO(audio_bytes), format="mp3")
combined += segment
return combined
The tqdm progress bar gives you visual feedback while the script processes each chunk.
Step 5 – Export the Final MP3
def export_audiobook(audio: AudioSegment, output_path: str):
audio.export(output_path, format="mp3", bitrate="192k")
print(f"✅ Audiobook saved to {output_path}")
if __name__ == "__main__":
# 1️⃣ Load & clean
text = load_and_clean("my_book.txt")
# 2️⃣ Chunk
chunks = chunk_text(text)
# 3️⃣ Generate + concatenate
final_audio = build_audiobook(chunks)
# 4️⃣ Export
export_audiobook(final_audio, "my_book_audiobook.mp3")
Run the script, sit back, and let ElevenLabs do the heavy lifting. For a 100‑page novel you’ll typically see the process finish in a few minutes, depending on your internet speed and the number of chunks.
Tweaking Voice Settings
ElevenLabs offers two key knobs:
| Setting | Range | What It Does |
|---|---|---|
stability |
0 – 1 | Controls how consistent the voice stays across sentences. Higher values reduce wobble. |
similarity_boost |
0 – 1 | Pushes the output closer to the target voice’s timbre. Useful when you’ve cloned a voice and want a tighter match. |
Feel free to experiment. For a calm narration you might lower stability a bit to add subtle intonation; for a dramatic reading, crank similarity_boost up to 0.95.
Going Beyond: Adding Chapter Marks
If you want chapter navigation in the final MP3, you can embed ID3 tags using mutagen:
from mutagen.mp3 import MP3
from mutagen.id3 import TIT2, TALB, TPE1, CHAP, CTOC
def add_chapter_tags(mp3_path, chapters):
audio = MP3(mp3_path, ID3=mutagen.id3.ID3)
# Basic tags
audio["TIT2"] = TIT2(encoding=3, text="My Book Title")
audio["TPE1"] = TPE1(encoding=3, text="Author Name")
# Add chapter frames (requires start/end timestamps in ms)
# This is left as an exercise – the ElevenLabs API already gives you timestamps per chunk.
audio.save()
Adding chapter frames is optional but gives listeners a nice way to skip around.
Deploying as a Small Web Service
If you’d rather expose this functionality via an HTTP endpoint (e.g., for a SaaS product), a Flask wrapper is only a few lines:
from flask import Flask, request, send_file
app = Flask(__name__)
@app.route("/generate", methods=["POST"])
def generate():
data = request.json
text = data.get("text", "")
chunks = chunk_text(text)
audio = build_audiobook(chunks)
out_path = "temp.mp3"
audio.export(out_path, format="mp3")
return send_file(out_path, mimetype="audio/mpeg", as_attachment=True)
if __name__ == "__main__":
app.run(debug=True)
Remember to keep your ElevenLabs API key secret – store it in environment variables or a secrets manager when you move to production.
Wrap‑Up
You now have a fully functional audiobook generator that:
- Leverages ElevenLabs for state‑of‑the‑art voice synthesis (check out the API at https://try.elevenlabs.io/kr07zfuqn1bp).
- Handles text cleaning, chunking, and audio concatenation automatically.
- Can be run locally, containerized, or exposed as a micro‑service.
The beauty of ElevenLabs is that you get a human‑like voice without the hassle of training deep learning models yourself. Whether you’re building a personal tool, an educational platform, or a commercial audiobook service, this pipeline gives you a solid foundation.
Ready to give it a spin?
Grab your free ElevenLabs API key, plug it into the script, and start turning your favorite reads into spoken gold. Happy coding, and enjoy the sound of your own words! 🚀
Try ElevenLabs now: https://try.elevenlabs.io/kr07zfuqn1bp
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.