DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

How to Add AI Narration to Your Blog Posts

Why Add AI Narration to Your Blog?

If you’ve ever scrolled through a long‑form article and thought, “I wish I could listen to this while I’m on the go,” you’re not alone. Audio versions boost accessibility, increase time‑on‑page, and can even improve SEO. With modern text‑to‑speech (TTS) services, you can generate natural‑sounding narration in minutes—no professional voice actor required.

In this post I’ll walk you through a complete, developer‑friendly workflow for turning any Markdown post into a spoken version. We’ll cover:

  1. Picking a TTS provider (I’ll be using ElevenLabs for its realistic voices and easy API).
  2. Setting up an API key and optional voice cloning.
  3. Generating audio with a simple Python script (or a curl command if you prefer the terminal).
  4. Embedding the resulting MP3 into a static site or a CMS‑driven blog.

Grab your favorite coffee, fire up a terminal, and let’s get talking.


1. Choose the Right TTS Engine

There are a handful of solid options on the market—Google Cloud TTS, Amazon Polly, Azure Speech, and a few startups. What sets ElevenLabs apart is its focus on expressive, human‑like speech and a straightforward REST API that works well for both one‑off posts and large‑scale batch jobs. You can sign up for a free tier and get an API key instantly.

👉 Try ElevenLabs here: https://try.elevenlabs.io/kr07zfuqn1bp

If you need a custom voice that sounds like you (or a brand mascot), ElevenLabs also offers voice cloning for a modest additional cost. The workflow is the same; you just upload a few minutes of reference audio and receive a unique voice ID.


2. Get Your API Key

  1. Register at the link above.
  2. Navigate to Dashboard → API Keys.
  3. Click Create New Key, give it a name (e.g., “BlogNarration”), and copy the resulting string.

Store this key securely—preferably in an environment variable called ELEVENLABS_API_KEY. Never commit it to source control.

export ELEVENLABS_API_KEY="your_secret_key_here"
Enter fullscreen mode Exit fullscreen mode

3. Prepare Your Blog Content

Most static site generators (Hugo, Jekyll, Astro) store posts as Markdown files. You can feed the raw text directly to the TTS endpoint, but a little cleanup helps:

import re

def clean_markdown(md: str) -> str:
    # Remove front‑matter (--- block)
    md = re.sub(r'^---\n.*?\n---\n', '', md, flags=re.DOTALL)
    # Strip markdown syntax (headings, links, code fences)
    md = re.sub(r'[`*_>#-]', '', md)
    # Collapse multiple spaces/newlines
    md = re.sub(r'\s+', ' ', md).strip()
    return md
Enter fullscreen mode Exit fullscreen mode

Save the cleaned string to a variable called text. This will be the input for the voice engine.


4. Generate Audio with Python

Below is a minimal script that sends the text to ElevenLabs, receives an MP3 stream, and writes it to disk. It also demonstrates how to use a cloned voice if you have one.

import os
import requests

ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")
VOICE_ID = "default"  # Replace with your cloned voice ID if you have one

def synthesize(text: str, output_path: str):
    url = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}"
    headers = {
        "xi-api-key": ELEVENLABS_API_KEY,
        "Content-Type": "application/json"
    }
    payload = {
        "text": text,
        "voice_settings": {
            "stability": 0.75,
            "similarity_boost": 0.85
        }
    }

    response = requests.post(url, json=payload, headers=headers, stream=True)
    response.raise_for_status()

    with open(output_path, "wb") as f:
        for chunk in response.iter_content(chunk_size=8192):
            f.write(chunk)

    print(f"✅ Audio saved to {output_path}")

if __name__ == "__main__":
    # Load and clean your markdown file
    with open("my-post.md", "r", encoding="utf-8") as f:
        raw_md = f.read()
    clean_text = clean_markdown(raw_md)

    # Call the API
    synthesize(clean_text, "my-post.mp3")
Enter fullscreen mode Exit fullscreen mode

What’s happening?

  • VOICE_ID can be "default" (ElevenLabs’ built‑in voice) or the ID of a cloned voice you created.
  • stability and similarity_boost tweak the prosody; feel free to experiment.
  • The API returns a streaming MP3, which we write directly to my-post.mp3.

Curl Alternative

If you’re comfortable with the command line, the same request can be done with curl:

curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/default" \
  -H "xi-api-key: $ELEVENLABS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
        "text": "Your cleaned blog post goes here.",
        "voice_settings": {"stability":0.75,"similarity_boost":0.85}
      }' \
  --output my-post.mp3
Enter fullscreen mode Exit fullscreen mode

Just replace the "text" field with your cleaned markdown string (or pipe it from a file using $(cat cleaned.txt)).


5. Automate for a Whole Site

If you have dozens of posts, you probably don’t want to run the script manually each time. Here’s a quick Bash loop that processes every .md file in a folder:

#!/usr/bin/env bash
set -euo pipefail

export ELEVENLABS_API_KEY="your_secret_key_here"

for md in content/*.md; do
  base=$(basename "$md" .md)
  cleaned=$(python -c "
import sys, re, pathlib;
md = pathlib.Path('$md').read_text();
md = re.sub(r'^---\n.*?\n---\n', '', md, flags=re.DOTALL);
md = re.sub(r'[`*_>#-]', '', md);
print(' '.join(md.split()));
")
  curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/default" \
    -H "xi-api-key: $ELEVENLABS_API_KEY" \
    -H "Content-Type: application/json" \
    -d "{\"text\":\"$cleaned\",\"voice_settings\":{\"stability\":0.75,\"similarity_boost\":0.85}}" \
    --output "static/audio/$base.mp3"
  echo "✅ Generated audio for $base"
done
Enter fullscreen mode Exit fullscreen mode

Add this script to your build pipeline (e.g., a npm run build step or a GitHub Action) and every new post will automatically get an accompanying MP3.


6. Embed the Audio in Your Blog

Most static site generators let you inject raw HTML into a post. Here’s a minimal snippet you can paste at the top or bottom of your article:

<audio controls preload="metadata" style="width: 100%; margin: 1rem 0;">
  <source src="/audio/my-post.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>
Enter fullscreen mode Exit fullscreen mode

If you’re using a CMS like WordPress, just add the same <audio> tag in the editor’s “HTML” view. The controls attribute gives readers play/pause, volume, and download options out of the box.

Optional: Add a “Listen” Button

For a cleaner UI you can hide the default controls and provide a custom button:

<button id="playBtn">▶️ Listen to this post</button>
<audio id="postAudio" preload="metadata" style="display:none;">
  <source src="/audio/my-post.mp3" type="audio/mpeg">
</audio>

<script>
const btn = document.getElementById('playBtn');
const audio = document.getElementById('postAudio');

btn.addEventListener('click', () => {
  if (audio.paused) {
    audio.play();
    btn.textContent = '⏸️ Pause';
  } else {
    audio.pause();
    btn.textContent = '▶️ Listen to this post';
  }
});
</script>
Enter fullscreen mode Exit fullscreen mode

Now you have a sleek, one‑click listening experience.


7. Fine‑Tuning the Voice

ElevenLabs lets you adjust a handful of parameters on the fly:

Parameter Typical Range What It Does
stability 0.0 – 1.0 Controls how consistent the voice stays.
similarity_boost 0.0 – 1.0 Makes the voice sound more like the base model (higher = more “human”).
style (beta) chat, narration, advertising Alters pacing and emphasis for different contexts.

Experiment with a short paragraph until you land on a tone that matches your brand. The changes are immediate—no re‑training needed.


8. Handling Large Articles

ElevenLabs caps a single request at roughly 5 000 characters. For longer posts, split the text into logical chunks (e.g., per heading) and concatenate the resulting MP3s. Here’s a quick Python helper:

def chunk_text(text, max_len=4500):
    sentences = re.split(r'(?<=[.!?]) +', text)
    chunks = []
    current = ""
    for s in sentences:
        if len(current) + len(s) + 1 > max_len:
            chunks.append(current.strip())
            current = s
        else:
            current += " " + s
    if current:
        chunks.append(current.strip())
    return chunks
Enter fullscreen mode Exit fullscreen mode

Loop over chunk_text(clean_text) and call synthesize for each piece, then merge the MP3s using ffmpeg:

ffmpeg -i "concat:part1.mp3|part2.mp3|part3.mp3" -c copy full-post.mp3
Enter fullscreen mode Exit fullscreen mode

9. Keep Accessibility in Mind

While AI narration is a fantastic supplement, it doesn’t replace proper alt text for images or transcripts for the hearing impaired. Consider generating a plain‑text transcript (the same cleaned markdown you fed the TTS engine) and linking it under the audio player:

<p><a href="/transcripts/my-post.txt">Download transcript</a></p>
Enter fullscreen mode Exit fullscreen mode

10. Wrap‑Up & Next Steps

You now have a full pipeline:

  1. Write your post in Markdown.
  2. Clean the text and feed it to ElevenLabs.
  3. Generate an MP3 (or a series of MP3s) via a simple script or curl.
  4. Embed the audio with an <audio> tag or a custom button.
  5. Deploy – your readers can listen instantly.

Give it a spin on your next article and watch the engagement metrics climb. If you need a custom brand voice, try cloning a few minutes of your own narration; the results are surprisingly authentic.


Ready to give your blog a voice?

Head over to ElevenLabs, grab an API key, and start turning your written content into high‑quality audio today: https://try.elevenlabs.io/kr07zfuqn1bp

Happy coding—and happy listening!

Top comments (0)