Create an Interactive Audio Story Generator

Create an Interactive Audio Story Generator

https://ift.tt/Jumobvr

Overview

Picture a web app where someone enters a few prompts, selects a character’s voice, and immediately hears a short story brought to life. Thanks to today’s text-to-speech (TTS) APIs, this isn’t just a futuristic concept—you can put together a working version in an afternoon. In this guide, we’ll build an interactive audio story generator with a Python backend, a small JavaScript front end, and the TTS service from ElevenLabs.

Here’s what you’ll learn:

  • How to use the ElevenLabs API to create natural-sounding speech.
  • How to switch between voices or create a custom voice clone.
  • How to build a simple “choose-your-own-adventure” flow that responds to user decisions.
  • How to deliver generated audio to a browser for playback.

Let’s get started!

What You’ll Need

Requirement Purpose
Python 3.9+ Runs the server and handles HTTP requests.
FastAPI (or Flask) A lightweight web framework suited to asynchronous requests.
Node.js (optional) Useful if you’d rather run the front-end development server with npm run dev.
ElevenLabs API key An API key is required to use the ElevenLabs platform. Sign up using the affiliate link above to get started.
A modern browser Needed to check that audio plays correctly.

You can run the project in Docker if you like, but containerization isn’t necessary to follow the main steps.

Configure the ElevenLabs API

ElevenLabs provides a simple REST API. Once you have an API key, add it to an environment variable to avoid accidentally committing it to your project:

export ELEVENLABS_API_KEY="your_api_key_here"

Use this quick curl request to check that your key works:

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

If hello.wav sounds clear, you’re all set to continue. Change EXAMPLE_VOICE_ID to a voice ID from your ElevenLabs dashboard, such as 21m00Tcm4TlvDq8ikWJ.

Create Speech with Python

This basic FastAPI endpoint accepts a story excerpt, sends it to ElevenLabs for synthesis, and provides a temporary URL for the resulting audio.

# 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")

Start the application with:

uvicorn app:app --reload

A client can now send a POST request with JSON such as { "text": "Once upon a time..." } and get back a URL for the generated speech.

Create the Interactive Front-End

The user interface can be a single HTML page controlled by a little JavaScript. Users can enter a prompt, select a voice, and see new choices as the story progresses.

<!-- 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>

How does it work?

  1. The user enters an opening sentence or chooses the default text.
  2. The page sends that text to the /speak endpoint using a POST request.
  3. The server responds with a temporary MP3 URL, which the browser plays.
  4. The simple state machine in storyMap determines which choices appear next.
  5. Choosing an option calls /speak again, continuing the audio story.

You can expand storyMap into a richer branching story and store its data in a database or JSON file.

Optional: Create Custom Voices

ElevenLabs can also clone a voice from a short audio recording, typically around 30 seconds long. This can help you give different story characters distinct-sounding voices.

# 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)

Once you’ve created a voice clone, add its voice_id to the front-end <select> menu so users can try it out. Voice cloning is included in the ElevenLabs platform, alongside the neural speech models used above.

Bring the Pieces Together

  1. Launch the FastAPI app with uvicorn app:app --reload.
  2. Serve index.html from the project directory or use a static server such as python -m http.server.
  3. Visit the page in Chrome or Firefox. Enter an opening line, choose a voice, and listen as the story develops.
  4. Build on the example: add more branches, save choices in a database, or connect a ChatGPT-style text generator for dynamic storytelling.

You’ve now got a working voice-based interactive story generator. From here, you can adapt it for games, language practice, accessibility, and more.

Ideas for What to Do Next

  • Save story progress – track each user’s journey with SQLite or MongoDB.
  • Generate story text with AI – pair GPT-4 from OpenAI with ElevenLabs to create new content on demand.
  • Deploy your app – package it with Docker and host it on Render, Fly.io, or another cloud service.
  • Try different voices – explore the growing ElevenLabs voice library and experiment with delivery, speed, and emotion.

Get Started

Want to add realistic speech to your next project? Visit ElevenLabs, get an API key, and give it a try. The free tier is useful for prototyping, while voice cloning offers another way to create distinctive characters for interactive projects. Have fun building!

HI-FI News

via DEV Community https://dev.to

November 12, 2026 at 04:37AM