如何用 ElevenLabs 建立語音文件閲讀器
Build a Voice-Enabled Documentation Reader
這篇教學示範如何用 ElevenLabs TTS 將 Markdown 文件轉成分段 MP3,建立可本機執行的語音文件閲讀器。Python CLI 會移除 YAML front matter、按段落切分內容,再呼叫 ElevenLabs API 生成音訊;文章亦説明如何加入自訂語音及封裝工具。
Why a Voice‑Enabled Documentation Reader?
Reading long API references or onboarding guides on a screen can be tiring, especially when you’re multitasking. A voice‑enabled documentation reader lets developers listen to the content while they code, review pull requests, or even walk around the office. With modern text‑to‑speech (TTS) engines you can get natural‑sounding speech, custom voices, and even clone a brand‑specific voice for consistency across your product.
In this post you’ll learn how to:
- Hook up the powerful ElevenLabs TTS service (yes, the same tech behind many podcasts and audiobooks).
- Pull markdown files from a repo or local folder.
- Convert them to speech on the fly with a few lines of Python.
- (Optional) Use voice cloning to give your docs a unique personality.
The result is a tiny CLI tool you can run locally or ship as part of a CI pipeline to generate audio files for every new doc release.
Getting Started with ElevenLabs
First things first—sign up for an account at the official ElevenLabs portal: https://try.elevenlabs.io/kr07zfuqn1bp. After confirming your email you’ll land on the dashboard where you can create an API key. Keep this key secret; treat it like a password.
Tip: ElevenLabs offers a generous free tier (up to 10 k characters per month). For larger documentation sets you’ll probably want to upgrade, but the free tier is perfect for prototyping.
The Core Idea: Stream Docs → TTS → Audio
At a high level the workflow looks like this:
[Markdown File] → [Strip Front‑Matter] → [Chunk Text] → [ElevenLabs API] → [MP3 File]
Why chunk? ElevenLabs limits each request to ~5 k characters. Splitting the doc into logical sections (headings, code blocks, paragraphs) ensures we stay under the limit and retain natural pauses.
Setting Up the Project
# Create a fresh virtual environment
python -m venv .venv
source .venv/bin/activate
# Install the HTTP client we’ll use
pip install httpx tqdm python-dotenv
Create a .env file in the project root:
ELEVENLABS_API_KEY=your_api_key_here
We’ll use python-dotenv to load this automatically.
A Minimal Python Reader
Below is a fully‑working script that reads a markdown file, sends each chunk to ElevenLabs, and writes an MP3 per section.
# voice_reader.py
import os
import re
import httpx
from pathlib import Path
from dotenv import load_dotenv
from tqdm import tqdm
# Load API key from .env
load_dotenv()
API_KEY = os.getenv("ELEVENLABS_API_KEY")
if not API_KEY:
raise RuntimeError("Set ELEVENLABS_API_KEY in .env")
BASE_URL = "https://api.elevenlabs.io/v1"
VOICE_ID = "EXAVITQu4vr4xnSDxMaL" # default "Rachel" voice
HEADERS = {
"xi-api-key": API_KEY,
"Content-Type": "application/json",
}
def split_into_chunks(text: str, max_len: int = 4000) -> list[str]:
"""Break text into ≤max_len chunks, preferring paragraph boundaries."""
paragraphs = re.split(r"\n\s*\n", text.strip())
chunks, current = [], ""
for para in paragraphs:
if len(current) + len(para) + 2 > max_len:
chunks.append(current.strip())
current = ""
current += para + "\n\n"
if current:
chunks.append(current.strip())
return chunks
def synthesize(text: str, output_path: Path):
payload = {
"text": text,
"voice_settings": {"stability": 0.75, "similarity_boost": 0.85},
}
url = f"{BASE_URL}/text-to-speech/{VOICE_ID}"
response = httpx.post(url, json=payload, headers=HEADERS, timeout=60)
response.raise_for_status()
output_path.write_bytes(response.content)
def main(doc_path: str, out_dir: str):
doc = Path(doc_path).read_text(encoding="utf-8")
# Remove any front‑matter (e.g., Jekyll/YAML)
doc = re.sub(r"^---\n.*?\n---\n", "", doc, flags=re.DOTALL)
chunks = split_into_chunks(doc)
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
for i, chunk in enumerate(tqdm(chunks, desc="Generating audio")):
out_file = out_dir / f"section_{i+1:02}.mp3"
synthesize(chunk, out_file)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Convert Markdown docs to speech")
parser.add_argument("doc", help="Path to the markdown file")
parser.add_argument("-o", "--output", default="audio", help="Output folder")
args = parser.parse_args()
main(args.doc, args.output)
How It Works
- Load the doc – Strips any YAML front‑matter that many static‑site generators add.
- Chunk it – Keeps each request under ElevenLabs’ size limit while preserving paragraph breaks.
-
POST to
/text-to-speech/{voice_id}– The endpoint returns raw MP3 bytes, which we write straight to disk. -
Progress bar –
tqdmgives a nice CLI progress indicator.
Run it like this:
python voice_reader.py docs/api_reference.md -o api_audio
You’ll end up with api_audio/section_01.mp3, section_02.mp3, … ready for playback.
Adding a Custom Voice with Voice Cloning
ElevenLabs also supports voice cloning – you can upload a short (≈30 s) sample of a speaker’s voice and receive a voice_id you can reuse forever. This is great if you want your docs to sound like your CTO, a brand mascot, or even a synthetic “robot” voice.
Quick Steps
- Record a clean WAV/MP3 of the target speaker (no background noise).
- Use the Clone Voice endpoint:
curl -X POST "https://api.elevenlabs.io/v1/voices/add" \
-H "xi-api-key: $ELEVENLABS_API_KEY" \
-F "name=MyBrandVoice" \
-F "files=@/path/to/sample.wav"
The response contains a new voice_id. Replace the VOICE_ID constant in voice_reader.py with this ID, and you’ll instantly start generating audio in your custom voice.
Pro tip: Keep the sample under 2 minutes for fastest processing. ElevenLabs will give you a preview link so you can approve the cloned voice before using it in production.
Deploying as a Tiny CLI Tool
If you want to share this with teammates, package it with setuptools:
# setup.py
from setuptools import setup, find_packages
setup(
name="doc-voice-reader",
version="0.1.0",
packages=find_packages(),
install_requires=["httpx", "tqdm", "python-dotenv"],
entry_points={"console_scripts": ["docvoice=voice_reader:main"]},
)
After pip install . you can call docvoice path/to/file.md from anywhere. Pair it with a simple shell alias to listen while you code:
alias listendoc='docvoice $1 && mpv $(ls -1 *.mp3 | sort -V | tail -n 1)'
Now listendoc docs/guide.md will generate the audio and immediately start playback with mpv.
Going Further
-
Chunk by heading: Use a markdown parser (like
markdown-it-py) to split on##and###headings, giving you one audio file per section. - Cache results: Store a hash of the source text and skip regeneration if the doc hasn’t changed.
- Streaming: Instead of saving MP3 files, pipe the response directly to a player for real‑time listening.
-
Multilingual support: ElevenLabs supports several languages; just pass the
languageparameter in the payload.
Wrap‑Up & Call‑to‑Action
You now have a functional voice‑enabled documentation reader built on top of ElevenLabs’ state‑of‑the‑art TTS engine. Whether you’re creating onboarding podcasts, accessibility‑first docs, or just want to give yourself a hands‑free way to skim through API specs, the pieces are all here.
Ready to give your docs a voice? Grab your free ElevenLabs API key and start experimenting: https://try.elevenlabs.io/kr07zfuqn1bp. Happy coding, and enjoy listening!
來源:DEV Community · dev.to