Create an Interactive Audio Story Generator

创建一个交互式音频故事生成器
https://ift.tt/Jumobvr
简介
想象一下,有这样一款 Web 应用:用户输入几个提示词,选择角色的声音,立刻就能听到一段配音完整的短篇故事。借助现代文本转语音(TTS)API,这已经不再是遥不可及的未来演示,而是你一个下午就能搭建出来的东西。在这篇文章中,我们将使用 Python 构建后端,用少量 JavaScript 编写前端,并借助 ElevenLabs 强大的 TTS 平台,制作一个交互式音频故事生成器。
你将学会如何:
- 调用 ElevenLabs API,合成听起来自然的语音。
- 在多种声音之间切换,甚至克隆自定义声音。
- 构建一个简单的“选择你自己的冒险”循环,根据用户的选择做出响应。
- 将音频文件发送回浏览器,立即播放。
开始吧!
准备工作
| 所需条件 | 用途 |
|---|---|
| Python 3.9+ | 运行服务器并发送 HTTP 请求。 |
| FastAPI(或 Flask) | 轻量级 Web 框架,能够很好地配合异步请求。 |
| Node.js(可选) | 如果你更喜欢使用 npm run dev,可用它来运行前端开发服务器。 |
| ElevenLabs API 密钥 | 你需要一个 ElevenLabs 平台的 API 密钥。通过上方的推广链接注册,即可立即获取。 |
| 现代浏览器 | 用于测试音频播放。 |
如果你熟悉 Docker,可以将整个项目容器化,但理解核心概念并不需要这么做。
设置 ElevenLabs API
ElevenLabs 提供了简单易用的 REST 接口。获取 API 密钥后,请将其存储在环境变量中,以免不小心将它提交到代码仓库:
export ELEVENLABS_API_KEY="your_api_key_here"
运行一条简单的 curl 命令即可验证一切是否正常:
curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/EXAMPLE_VOICE_ID" \
-H "xi-api-key: $ELEVENLABS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "Hello, world! This is a test of ElevenLabs TTS.",
"model_id": "eleven_monolingual_v1"
}' \
--output hello.wav
如果你听到清晰的 hello.wav 音频文件,就可以进入下一步了。将 EXAMPLE_VOICE_ID 替换为你在 ElevenLabs 控制面板中看到的任意声音 ID(例如 21m00Tcm4TlvDq8ikWJ)。
使用 Python 生成语音
下面是一个精简的 FastAPI 接口示例:它接收一段故事文本,调用 ElevenLabs,并返回生成音频的临时 URL。
# app.py
import os
import uuid
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import httpx
app = FastAPI()
ELEVEN_API_KEY = os.getenv("ELEVENLABS_API_KEY")
BASE_URL = "https://api.elevenlabs.io/v1"
class StoryChunk(BaseModel):
text: str
voice_id: str = "21m00Tcm4TlvDq8ikWJ" # default voice
@app.post("/speak")
async def speak(chunk: StoryChunk):
endpoint = f"{BASE_URL}/text-to-speech/{chunk.voice_id}"
payload = {
"text": chunk.text,
"model_id": "eleven_monolingual_v1"
}
headers = {
"xi-api-key": ELEVEN_API_KEY,
"Content-Type": "application/json"
}
async with httpx.AsyncClient() as client:
resp = await client.post(endpoint, json=payload, headers=headers)
if resp.status_code != 200:
raise HTTPException(status_code=resp.status_code,
detail="ElevenLabs synthesis failed")
# Save to a temp file
file_id = f"{uuid.uuid4()}.mp3"
with open(f"/tmp/{file_id}", "wb") as f:
f.write(resp.content)
return {"audio_url": f"/audio/{file_id}"}
@app.get("/audio/{file_id}")
async def get_audio(file_id: str):
file_path = f"/tmp/{file_id}"
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="Audio not found")
return fastapi.responses.FileResponse(file_path, media_type="audio/mpeg")
启动服务器:
uvicorn app:app --reload
现在,任何客户端都可以发送类似 { "text": "Once upon a time..." } 的 JSON POST 请求,并获得一个用于播放语音片段的 URL。
构建交互循环(前端)
前端是一个单页 HTML 页面,配有一个简易的 JavaScript 控制器。用户可以输入提示词、选择声音,随后页面会根据故事状态显示下一组选项。
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Audio Story Generator</title>
<style>
body { font-family: sans-serif; max-width: 600px; margin: 2rem auto; }
#choices button { margin: 0.5rem; }
</style>
</head>
<body>
<h1>Interactive Audio Story</h1>
<textarea id="prompt" rows="3" placeholder="Write your opening line..."></textarea><br>
<select id="voice">
<option value="21m00Tcm4TlvDq8ikWJ">Narrator (default)</option>
<option value="EXAMPLE_VOICE_2">Mysterious Voice</option>
</select>
<button id="startBtn">Start</button>
<div id="player"></div>
<div id="choices"></div>
<script>
const startBtn = document.getElementById('startBtn');
const prompt = document.getElementById('prompt');
const voice = document.getElementById('voice');
const playerDiv = document.getElementById('player');
const choicesDiv = document.getElementById('choices');
async function speak(text) {
const resp = await fetch('/speak', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text, voice_id: voice.value })
});
const data = await resp.json();
const audio = new Audio(data.audio_url);
playerDiv.innerHTML = '';
playerDiv.appendChild(audio);
audio.play();
}
// Simple story engine – in reality you’d store state on the server
const storyMap = {
"start": ["You stand at a crossroads. Go left or right?"],
"left": ["A dragon appears! Fight or flee?"],
"right": ["You find a treasure chest. Open it or ignore?"]
};
function presentChoices(key) {
choicesDiv.innerHTML = '';
const options = key === 'start' ? ['left', 'right'] :
key === 'left' ? ['fight', 'flee'] :
['open', 'ignore'];
options.forEach(opt => {
const btn = document.createElement('button');
btn.textContent = opt;
btn.onclick = async () => {
await speak(storyMap[opt] ? storyMap[opt][0] : `You chose ${opt}.`);
presentChoices(opt);
};
choicesDiv.appendChild(btn);
});
}
startBtn.onclick = async () => {
await speak(prompt.value || "Once upon a time...");
presentChoices('start');
};
</script>
</body>
</html>
运行过程是怎样的?
- 用户输入故事开头,或使用默认文本。
- 前端将这段文本 POST 到
/speak。 - 服务器返回一个临时 MP3 URL,浏览器随即播放音频。
- 一个非常简单的状态机(
storyMap)决定接下来显示哪些选项。 - 每次点击按钮都会再次调用
/speak,形成流畅的音频交互循环。
你可以用更复杂的分支叙事替换 storyMap,并将其存储在数据库或 JSON 文件中。
可选:克隆声音,打造个性化角色
ElevenLabs 还支持从一段较短的音频样本(通常约 30 秒)中克隆声音。这非常适合为故事中的每个角色赋予独特的音色。
# clone_voice.py
import os, httpx
API_KEY = os.getenv("ELEVENLABS_API_KEY")
BASE = "https://api.elevenlabs.io/v1"
def clone(name: str, audio_path: str):
with open(audio_path, "rb") as f:
files = {"audio_file": (audio_path, f, "audio/wav")}
data = {"name": name}
headers = {"xi-api-key": API_KEY}
resp = httpx.post(f"{BASE}/cloning", headers=headers, data=data, files=files)
resp.raise_for_status()
return resp.json()["voice_id"]
voice_id = clone("Hero", "hero_sample.wav")
print("New voice ID:", voice_id)
克隆完成后,你可以将新的 voice_id 添加到前端的 <select> 列表中,让用户听到自己定制的角色开口说话。声音克隆接口属于 ElevenLabs 服务套件的一部分,因此你可以使用熟悉的高品质神经网络模型。
整合起来
-
启动 FastAPI 服务器(
uvicorn app:app --reload)。 -
提供
index.html:从同一目录提供,或通过静态文件服务器提供(使用python -m http.server即可)。 - 在 Chrome/Firefox 中打开页面。输入故事开头,选择一种声音,然后听着音频,看故事逐步展开。
- 持续迭代:添加更多分支,将用户选择存入数据库,或者集成类似 ChatGPT 的文本生成器,让故事真正动态起来。
就是这么简单!现在你已经拥有一个可用的、由语音驱动的交互式故事生成器,还可以将它扩展为游戏、语言学习工具或无障碍体验。
后续步骤
- 保存故事进度——使用 SQLite 或 MongoDB 记录每位用户的故事路径。
- 添加 AI 文本生成——将 OpenAI 的 GPT-4 与 ElevenLabs 结合,实时生成故事内容。
- 部署——使用 Docker 将应用容器化,并部署到 Render、Fly.io 或任何云服务商。
- 探索更多声音——ElevenLabs 提供不断扩充的富有表现力的声音库;你可以尝试不同的语气、语速和情绪。
行动起来
准备好为你的项目赋予自然的声音了吗?前往 ElevenLabs 获取 API 密钥,现在就开始构建吧。平台提供的慷慨免费额度让你可以轻松制作原型,而声音克隆功能则能为任何交互体验添加真正独特的角色。祝编码愉快!
HI-FI News
来源:DEV Community https://dev.to
2026年11月12日 上午04:37
November 12, 2026 at 04:37AM
-
Product on sale
Audiophile Vinyl Records Cleaning BundleOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Product on sale
Easy Start Vinyl Records Cleaning KitOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Vinyl Records Cleaner Easy Groove Concentrate€34.95 incl. VAT -
Easy Groove Super Set€199.00 incl. VAT -
Easy Groove Enzycaster – vinyl records prewash cleaner€34.95 incl. VAT -
Easy Groove Extreme MK. II- vinyl records prewash cleaner€45.00 incl. VAT -
Vinyl Records Cleaner – Easy Groove Virgin Concentrate€35.00 incl. VAT -
Easy Groove Spray&Wipe vinyl records cleaner€34.95 incl. VAT








