AI Podcast Generator: Build One with ElevenLabs
Build an AI podcast generator with Python, an LLM, and ElevenLabs. Generate a script, synthesize speech, join audio, and plan for reliable publishing.

Build an AI Podcast Generator with Python and ElevenLabs
An AI podcast generator can turn a topic into a narrated audio draft in minutes. But a finished, publishable episode isn't "just one API call." You still have to write the script, check what it claims, pick a voice, manage the audio files, and listen for issues the HTTP response won't tell you about.
This tutorial focuses on the practical core: Python sends a topic to a language model, splits the script into segments, asks ElevenLabs to synthesize each segment, and uses FFmpeg to produce one MP3. The setup stays small enough to run locally, but the structure is meant to make the real failure points easier to see - and easier to fix.
What an AI podcast generator does and where it fails
The pipeline is straightforward: generate text, convert that text to speech, then join the resulting audio segments. The LLM provides the script, ElevenLabs provides the voice, and FFmpeg does the audio combining. Python ties it all together and manages the intermediate files.
Keeping those steps separate is actually helpful. If the script doesn't work, you can revise the prompt without touching your audio code. If a voice mispronounces something, you can regenerate just the affected segment. And cost-wise, it's easier to reason about because you're dealing with separate text-generation and speech-synthesis requests.
What it won't do for you is editorial judgment. A model can make things up, flatten nuance, repeat itself, or produce sentences that look fine on screen but sound awkward when spoken. A voice can get a product name wrong or stress the wrong words. Then you concatenate everything - and none of those problems magically disappear.
So treat the first output as a production draft, not an episode ready for release. At minimum, review the factual claims, listen to the full MP3, and keep a human approval step before you publish. This matters a lot for news, health, finance, and anything where a wrong statement could cause real harm.
A good way to think about this is like a small build system:
- Input: a topic, audience, length, and editorial brief.
- Text artifact: a script you can review and save.
- Audio artifacts: one file per segment, so you can retry failures without starting over.
- Final artifact: a joined episode that you've listened to and run through a basic technical check.
The example uses a short prompt and a handful of paragraphs, which is fine for demonstrating the flow. In a real workflow, how clear your brief is (and how you review) usually matters more than tweaking another model parameter. Start with a clean format and a human checkpoint; automate more only after you've figured out what needs to stay consistent.
What you need before building
You need Python 3.9 or later, an API key for a language model, an ElevenLabs API key, and FFmpeg installed and available on your command line. Git is optional, but it's useful if you plan to iterate on prompts, voices, or processing settings.
Install the Python dependencies in a virtual environment:
python -m venv .venv
source .venv/bin/activate
python -m pip install httpx
On Windows, activate the environment with .venv\Scripts\activate. Install FFmpeg with your operating system's package manager, then verify that ffmpeg -version runs. The script calls FFmpeg as a subprocess, so it needs to be on your process path.
Set credentials as environment variables (not in source code):
export OPENAI_API_KEY="your-openai-key"
export ELEVENLABS_API_KEY="your-elevenlabs-key"
export ELEVENLABS_VOICE_ID="your-voice-id"
On Windows PowerShell, use $env:OPENAI_API_KEY="your-openai-key" and the equivalent commands for the other variables. For a deployed service, use your hosting platform's secret-management features. Don't commit a .env file with real credentials.
The voice ID is configurable because one voice won't necessarily fit every show. Check that your account can access the selected voice and that your use matches the provider's terms. If you use voice cloning, get explicit permission from the person you're cloning. "Available" doesn't automatically mean "appropriate."
Before generating a full episode, test with a short paragraph. Confirm your keys work, the selected voice is available, and the returned audio sounds acceptable. This catches configuration and access problems without burning credits on a long script.
How to generate a script and synthesize speech
The example below uses an LLM chat-completions request and an ElevenLabs text-to-speech request. The model name is configurable so you can pick a supported model for your account. The code also sets request timeouts and checks that required configuration exists.
import os
import pathlib
import uuid
import httpx
OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
ELEVENLABS_API_KEY = os.environ["ELEVENLABS_API_KEY"]
VOICE_ID = os.environ["ELEVENLABS_VOICE_ID"]
MODEL = os.getenv("OPENAI_MODEL", "gpt-4o")
client = httpx.Client(timeout=httpx.Timeout(60.0, connect=10.0))
def generate_script(topic: str, paragraphs: int = 5) -> list[str]:
prompt = (
f"Write a conversational podcast script about: {topic}. "
f"Return exactly {paragraphs} paragraphs, each around 40-60 words. "
"Use a brief introduction, clear transitions, and a concise ending. "
"Do not include headings, stage directions, or unsupported statistics."
)
response = client.post(
"https://api.openai.com/v1/chat/completions",
headers={"Authorization": f"Bearer {OPENAI_API_KEY}"},
json={
"model": MODEL,
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.5,
},
)
response.raise_for_status()
content = response.json()["choices"][0]["message"]["content"]
paragraphs_out = [part.strip() for part in content.split("\n\n") if part.strip()]
if not paragraphs_out:
raise ValueError("The model returned an empty script")
return paragraphs_out
def synthesize_paragraph(text: str, output_dir: pathlib.Path) -> pathlib.Path:
response = client.post(
f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}",
headers={"xi-api-key": ELEVENLABS_API_KEY},
json={
"text": text,
"voice_settings": {
"stability": 0.75,
"similarity_boost": 0.85,
},
},
)
response.raise_for_status()
output_dir.mkdir(parents=True, exist_ok=True)
path = output_dir / f"{uuid.uuid4().hex}.mp3"
path.write_bytes(response.content)
return path
The paragraph split assumes the model separates segments with blank lines. That's convenient for a demo, but it's not a durable "data format." A model might add a heading, change spacing, or return fewer paragraphs than requested. In a production workflow, ask for structured output and validate it before sending anything to speech.
The prompt uses approximate word counts because long blocks are harder to review and retry. It also avoids requesting exact factual detail without sources. If you need current or verifiable claims, add a research-and-citation step, then review that material before you synthesize.
Also: a fluent voice doesn't make a claim more reliable. It just makes the delivery smoother.
Finally, temperature isn't a magic "quality" knob. Lower values can be more consistent; higher values add variation. Neither setting guarantees factual accuracy or good spoken pacing. Read the script aloud (or listen to a short synthesized sample) before generating the whole episode.
How to combine audio and run the pipeline
Once each paragraph is synthesized, FFmpeg can join the files. The concat demuxer needs a text file that lists segments in order. Re-encoding the joined output is usually more forgiving than stream copying - especially when individual MP3 files have slightly different encoding details.
import subprocess
def combine_audio(files: list[pathlib.Path], output: pathlib.Path) -> None:
if not files:
raise ValueError("No audio files to combine")
output.parent.mkdir(parents=True, exist_ok=True)
list_file = files[0].parent / "concat-list.txt"
with list_file.open("w", encoding="utf-8") as handle:
for path in files:
handle.write(f"file '{path.name}'\n")
try:
subprocess.run(
[
"ffmpeg", "-y", "-f", "concat", "-safe", "0",
"-i", str(list_file), "-c:a", "libmp3lame", "-q:a", "2",
str(output.resolve()),
],
check=True,
cwd=files[0].parent,
capture_output=True,
text=True,
)
except subprocess.CalledProcessError as exc:
raise RuntimeError(f"FFmpeg failed: {exc.stderr}") from exc
finally:
list_file.unlink(missing_ok=True)
This uses UUID filenames from the synthesis step, so you don't end up with spaces or tricky quote characters in segment names. The output path is resolved before FFmpeg runs, so the command stays unambiguous even when the process runs from your temporary audio directory. Re-encoding takes a bit longer, but it tends to reduce surprises when you're joining separately generated MP3 files.
Now connect everything with a small orchestration function:
def create_podcast(topic: str, output_file: pathlib.Path) -> None:
work_dir = pathlib.Path("temp_audio")
work_dir.mkdir(parents=True, exist_ok=True)
audio_files = []
try:
paragraphs = generate_script(topic)
for paragraph in paragraphs:
audio_files.append(synthesize_paragraph(paragraph, work_dir))
combine_audio(audio_files, output_file)
finally:
for path in audio_files:
path.unlink(missing_ok=True)
work_dir.rmdir() if work_dir.exists() and not any(work_dir.iterdir()) else None
if __name__ == "__main__":
import sys
if len(sys.argv) != 3:
raise SystemExit("Usage: python podcast.py <topic> <output.mp3>")
create_podcast(sys.argv[1], pathlib.Path(sys.argv[2]))
print("Podcast draft generated")
Run it from the terminal:
python podcast.py "The future of quantum computing" output/quantum-computing.mp3
The finally block deletes temporary segments even if later stages fail. In a real system, deleting intermediates immediately can be the wrong trade-off. Keeping artifacts for a short time makes debugging easier and lets you retry only the failed synthesis request. Add a retention policy rather than letting temp audio pile up forever.
What to improve before publishing
This script proves the APIs connect. It doesn't prove your pipeline is ready for daily publishing. The next upgrades should target predictable operational problems, not add extra complexity "just because."
Add retries and useful failure handling
Network requests fail temporarily, and providers rate-limit. Add bounded retries for transient errors like timeouts and server errors, with a delay between attempts. Don't retry everything - an invalid key or a voice you don't have access to won't be fixed by repeating the same request.
Log what you need to diagnose issues (like the segment number and error category), but never log API keys or unnecessary personal data.
For longer scripts, save the text and a small manifest before synthesis. The manifest can include the topic, model, voice ID, segment order, and which segments completed. Then if the job stops midway, you have a clear recovery point.
Make editorial review part of the workflow
Save the script as a text file and require approval before generating audio when the topic is sensitive or your show has strict standards. For a lightweight setup, someone can review the script and listen to the final MP3. For batch production, a review queue is safer than auto-publishing everything.
When listening, watch for clipped starts, abrupt joins, uneven pacing, odd pronunciations, and stretches of excessive silence. A segment can sound fine on its own and still feel wrong next to the previous one. Your final listen is a quality check, not busywork.
Add production details selectively
You can prepend or append a recorded intro, outro, or music bed with FFmpeg. Keep the music low enough that it doesn't compete with speech, and confirm you have the rights to use it. Save the script alongside the MP3 so you can support edits, accessibility work, and correction requests later. If your publishing host supports metadata, add an episode title and any other relevant details during the publishing step.
Batch generation is also possible: read topics from a CSV and create one output file per row. But batch jobs multiply both successes and mistakes. Add limits, use clear filenames, monitor cost, and keep a review gate before you schedule recurring releases.
Track cost, latency, and provider dependencies
Each episode uses language-model usage and text-to-speech credits. The actual cost depends on script length, model, voice, and the provider's current pricing. Measure real usage on a short test episode, then estimate your monthly production cost before you commit to any release cadence. Also factor in retries, failed runs, and edits that require regenerating audio.
Lastly, this design depends on two external services. Their APIs, availability, and terms can change. Keep model names, voice IDs, and settings in configuration rather than hard-coding them throughout your code. That makes provider changes and voice updates easier to test - and easier to roll back.
Conclusion
A small Python pipeline is enough to turn a topic into a narrated podcast draft: generate a script with an LLM, synthesize it with ElevenLabs, and join the audio with FFmpeg. Splitting those steps makes the system easier to test, revise, and recover from failures.
The key boundary is editorial. Automation can save time assembling audio, but it doesn't replace fact-checking, rights management, or listening to the finished episode. Start with a short draft, validate the sound and cost, and only automate further once the workflow is actually reliable.