如何使用 ElevenLabs 建立 AI Podcast 生成器
Create an AI Podcast Generator with ElevenLabs
這份教學示範如何使用 Python,結合 OpenAI gpt-4o 與 ElevenLabs,按主題生成分段 Podcast 稿件,並將各段語音合併成 MP3。流程使用 ElevenLabs 的文字轉語音 API 和 ffmpeg 串接音訊,也可選用 ElevenLabs 的克隆語音。
Why an AI‑Powered Podcast?
Podcasts have exploded in popularity, but producing a full episode still means spending hours on research, script‑writing, recording, and editing. What if you could automate the whole pipeline? By combining a large‑language model (LLM) for content generation with a state‑of‑the‑art text‑to‑speech (TTS) service, you can spin up a fully voiced episode in minutes.
In this guide we’ll build a simple AI Podcast Generator that:
- Takes a topic prompt, asks an LLM (e.g., OpenAI’s
gpt‑4o) to write a short script. - Sends each paragraph to ElevenLabs – a high‑quality TTS platform that supports voice cloning.
- Concatenates the audio files into a single MP3 ready for publishing.
Everything is done with plain Python and a few command‑line tools, so you can drop it into a CI job, a serverless function, or your local dev environment.
Prerequisites
| What you need | Why |
|---|---|
| Python 3.9+ | Core language for the script |
| OpenAI API key (or any LLM you prefer) | Generates the podcast script |
| ElevenLabs API key | Turns text into lifelike speech |
ffmpeg (install via brew install ffmpeg / apt-get install ffmpeg) |
Merges multiple audio chunks into one file |
| Git (optional) | Version‑control the project |
If you don’t have an ElevenLabs account yet, grab a free trial through this affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp. It gives you 10 k characters of TTS credit and access to a handful of premium voices.
1. Get Your API Keys
# Save your keys as environment variables (never hard‑code them!)
export OPENAI_API_KEY="sk-..."
export ELEVENLABS_API_KEY="your-elevenlabs-key"
Both services use bearer tokens in the Authorization header, so keeping them in the environment is the safest approach.
2. Generate a Podcast Script
Below is a minimal wrapper around the OpenAI chat completion endpoint. It accepts a topic and returns a concise script split into paragraphs.
import os
import json
import httpx
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
HEADERS = {"Authorization": f"Bearer {OPENAI_API_KEY}"}
def generate_script(topic: str, paragraphs: int = 5) -> list[str]:
prompt = f"""You are a podcast host. Write a {paragraphs}-paragraph script about **{topic}**.
Each paragraph should be a self‑contained speaking segment (≈40‑60 words). Use a conversational tone, include a brief intro and a wrap‑up."""
payload = {
"model": "gpt-4o",
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.7,
}
resp = httpx.post("https://api.openai.com/v1/chat/completions", headers=HEADERS, json=payload)
resp.raise_for_status()
content = resp.json()["choices"][0]["message"]["content"]
# Split on double newlines to get separate paragraphs
return [p.strip() for p in content.split("\n\n") if p.strip()]
Tip: Adjust
temperaturefor more creative vs. deterministic output. For a news‑style podcast you might set it lower (0.3).
3. Turn Text into Speech with ElevenLabs
ElevenLabs provides a clean REST API that accepts plain text and returns an MP3 buffer. The following function wraps that call.
import pathlib
import uuid
ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")
ELEVEN_HEADERS = {
"xi-api-key": ELEVENLABS_API_KEY,
"Content-Type": "application/json",
}
VOICE_ID = "21m00Tcm4TlvDq8ikWAM" # Example: "Rachel" voice – change to your favorite
def synthesize_paragraph(text: str, output_dir: pathlib.Path) -> pathlib.Path:
payload = {
"text": text,
"voice_settings": {
"stability": 0.75,
"similarity_boost": 0.85
}
}
url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}"
resp = httpx.post(url, headers=ELEVEN_HEADERS, json=payload)
resp.raise_for_status()
# Save MP3 with a unique name
out_path = output_dir / f"{uuid.uuid4()}.mp3"
out_path.write_bytes(resp.content)
return out_path
You can experiment with different voice IDs or even upload a custom cloned voice through ElevenLabs’ dashboard. For a truly branded podcast, clone the voice of your host and reference it here – the same API call works with the cloned voice’s ID.
4. Stitch the Segments Together
ffmpeg makes concatenation painless. First, write a temporary file list, then run the command.
import subprocess
def combine_audio(files: list[pathlib.Path], output: pathlib.Path):
list_path = output.parent / "files.txt"
with open(list_path, "w", encoding="utf-8") as f:
for p in files:
f.write(f"file '{p.as_posix()}'\n")
# -safe 0 allows absolute paths
cmd = [
"ffmpeg", "-y", "-f", "concat", "-safe", "0",
"-i", str(list_path), "-c", "copy", str(output)
]
subprocess.run(cmd, check=True)
list_path.unlink() # clean up
5. The Full Pipeline
Putting everything together:
import pathlib
def create_podcast(topic: str, out_file: pathlib.Path):
work_dir = pathlib.Path("temp_audio")
work_dir.mkdir(exist_ok=True)
# 1️⃣ Generate script
paragraphs = generate_script(topic)
# 2️⃣ Synthesize each paragraph
audio_files = [
synthesize_paragraph(p, work_dir) for p in paragraphs
]
# 3️⃣ Combine into one episode
combine_audio(audio_files, out_file)
# Optional clean‑up
for f in work_dir.iterdir():
f.unlink()
work_dir.rmdir()
if __name__ == "__main__":
import sys
if len(sys.argv) != 3:
print("Usage: python podcast.py <topic> <output.mp3>")
sys.exit(1)
create_podcast(sys.argv[1], pathlib.Path(sys.argv[2]))
print("✅ Podcast generated!")
Run it like:
python podcast.py "The future of quantum computing" episode1.mp3
You’ll end up with an MP3 that sounds like a professional host, ready to upload to Spotify, Apple Podcasts, or any platform you prefer.
6. Going Further
| Idea | How to implement |
|---|---|
| Dynamic intros/outros | Pre‑record a short jingle, then prepend/append it with ffmpeg. |
| Voice cloning | Use ElevenLabs’ /v1/voices/add endpoint to upload a few minutes of your own voice, then replace VOICE_ID with the returned ID. |
| Batch generation | Loop over a CSV of topics and output a folder of episodes; hook the script into a CI pipeline for daily releases. |
| Transcripts | Save the generated script to a .txt file and embed it as podcast metadata (ID3 tags). |
| Multilingual episodes | Pass non‑English text directly to ElevenLabs; many voices support multiple languages out of the box. |
All of these extensions still rely on the same core building blocks: an LLM for content, ElevenLabs for realistic TTS, and a tiny amount of glue code.
7. Why ElevenLabs Rocks for This Use‑Case
- Human‑like prosody – The generated speech includes natural pauses, emphasis, and intonation that older TTS engines lack.
- Voice cloning – Upload a few recordings and create a unique “host” voice that matches your brand.
- Scalable pricing – Pay‑as‑you‑go credits make it cheap to spin up dozens of episodes per month.
If you’re looking for a plug‑and‑play solution that delivers studio‑grade audio without a massive learning curve, ElevenLabs is the go‑to service. Grab your free credits here: https://try.elevenlabs.io/kr07zfuqn1bp.
Wrap‑Up
You now have a fully functional AI Podcast Generator that can:
- Write a script from a simple topic prompt.
- Render each paragraph with lifelike speech.
- Stitch everything together into a publishable episode.
The code is deliberately straightforward so you can adapt it to your own workflow—whether you want to add background music, integrate a transcription service, or schedule daily releases.
Ready to give your listeners a voice they’ll love? Try ElevenLabs today, spin up a few episodes, and watch how quickly you can go from idea to on‑air content. Happy coding!
來源:DEV Community · dev.to