DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

Create a Voice-Powered News Reader App

Build a Voice‑Powered News Reader App

Today’s developers are looking for ways to deliver information in the most natural, hands‑free format. A voice‑powered news reader lets users stay informed while commuting, cooking, or doing any multitasking activity. In this article we’ll walk through building a simple news reader that fetches headlines, converts them to speech with ElevenLabs text‑to‑speech, and streams the audio directly to the user.

The stack is intentionally lightweight:

  • Python for the backend logic and API calls
  • ElevenLabs for high‑quality TTS and voice cloning
  • React (or vanilla JS) for the front‑end, but the concepts apply to any UI framework

Feel free to swap out the news source or the front‑end framework – the core ideas stay the same.


1. Why ElevenLabs?

ElevenLabs offers a modern TTS engine that delivers natural, expressive voices. Its API is simple, supports voice cloning, and the quality is on par with professional studios. The same service we’ll use to read headlines can also read long‑form articles, podcasts, or even custom scripts.

Tip: When you sign up at the official link, you’ll receive a free tier that lets you experiment with up to 5,000 characters per month.

Link: https://try.elevenlabs.io/kr07zfuqn1bp


2. Prerequisites

Tool Version
Python 3.10+ python --version
pip pip --version
Node.js 18+ node --version
(Optional) React npx create-react-app

Install the Python dependencies:

pip install requests flask python-dotenv
Enter fullscreen mode Exit fullscreen mode

Create a .env file in the root of your project:

ELEVENLABS_API_KEY=your_api_key_here
NEWSAPI_KEY=your_newsapi_key_here
Enter fullscreen mode Exit fullscreen mode

Replace the placeholders with the API keys you’ll receive from ElevenLabs and NewsAPI.


3. Fetching News

We’ll use the free tier of NewsAPI to pull the latest headlines. The endpoint is simple:

import os
import requests
from dotenv import load_dotenv

load_dotenv()
NEWSAPI_KEY = os.getenv("NEWSAPI_KEY")

def get_headlines():
    url = "https://newsapi.org/v2/top-headlines"
    params = {
        "country": "us",
        "pageSize": 5,
        "apiKey": NEWSAPI_KEY
    }
    resp = requests.get(url, params=params)
    resp.raise_for_status()
    articles = resp.json()["articles"]
    return [{"title": a["title"], "description": a["description"]} for a in articles]
Enter fullscreen mode Exit fullscreen mode

Now we have a list of headline objects that we can feed into ElevenLabs.


4. TTS with ElevenLabs

ElevenLabs exposes a REST API that accepts plain text and returns an audio stream. Below is a minimal Python wrapper.

import requests
import os

ELEVENLABS_API_KEY = os.getenv("ELEVENLABS_API_KEY")
ELEVENLABS_URL = "https://api.elevenlabs.io/v1/text-to-speech"

def synthesize(text, voice_id="21m0t3ylq6h2h5q6"):
    """
    voice_id: ID of the voice you want. 21m0t3ylq6h2h5q6 is the default
    """
    headers = {
        "xi-api-key": ELEVENLABS_API_KEY,
        "Content-Type": "application/json"
    }
    payload = {
        "text": text,
        "voice_settings": {"stability": 0.75, "similarity_boost": 0.75}
    }

    response = requests.post(ELEVENLABS_URL, headers=headers, json=payload)
    response.raise_for_status()
    return response.content  # raw audio bytes
Enter fullscreen mode Exit fullscreen mode

Note: Replace voice_id with any voice you’ve purchased or cloned. The default voice is fine for quick demos.


5. Streaming Audio in Flask

Let’s expose a /read endpoint that streams the synthesized audio back to the browser.

from flask import Flask, send_file, request, jsonify, Response
from io import BytesIO

app = Flask(__name__)

@app.route("/read", methods=["POST"])
def read():
    data = request.get_json()
    text = data.get("text", "")
    if not text:
        return jsonify({"error": "No text provided"}), 400

    audio_bytes = synthesize(text)
    return Response(
        audio_bytes,
        mimetype="audio/mpeg",
        headers={"Content-Disposition": "inline; filename=article.mp3"}
    )

if __name__ == "__main__":
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Start the server:

export FLASK_APP=app.py
flask run
Enter fullscreen mode Exit fullscreen mode

Now you can POST a JSON payload with a text field to http://localhost:5000/read and receive an MP3 stream.


6. Front‑End: React Example

A minimal React component that fetches headlines and reads them aloud.

import React, { useState } from "react";

export default function NewsReader() {
  const [headlines, setHeadlines] = useState([]);
  const [loading, setLoading] = useState(false);

  async function fetchHeadlines() {
    setLoading(true);
    const res = await fetch("/api/headlines");
    const data = await res.json();
    setHeadlines(data);
    setLoading(false);
  }

  async function readHeadline(text) {
    const res = await fetch("/read", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ text })
    });
    const audioBlob = await res.blob();
    const audioUrl = URL.createObjectURL(audioBlob);
    const audio = new Audio(audioUrl);
    audio.play();
  }

  return (
    <div>
      <h1>Voice‑Powered News Reader</h1>
      <button onClick={fetchHeadlines} disabled={loading}>
        {loading ? "Loading…" : "Get Headlines"}
      </button>
      <ul>
        {headlines.map((h, i) => (
          <li key={i}>
            <strong>{h.title}</strong>
            <p>{h.description}</p>
            <button onClick={() => readHeadline(`${h.title}. ${h.description}`)}>
              Read Aloud
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Back‑end route /api/headlines can simply proxy the get_headlines() function we defined earlier.


7. Voice Cloning (Optional)

If you want the news to sound like your own voice, ElevenLabs allows you to clone a voice with just a few minutes of audio. The process is:

  1. Record a 60‑second clip (preferably in a quiet environment).
  2. Upload the clip via the ElevenLabs console or API.
  3. Wait for the voice ID to be ready.

Once you have the voice_id, pass it to the synthesize() function:

audio_bytes = synthesize(text, voice_id="your_custom_voice_id")
Enter fullscreen mode Exit fullscreen mode

The result is a personalized, natural‑sounding news reader.


8. Deployment Tips

Platform Recommendation
Heroku Easy to spin up a Flask app, free tier for low traffic
Render Similar to Heroku but with better pricing for small projects
Vercel + Serverless Functions Use Next.js API routes for the TTS endpoint

Make sure you set environment variables in the deployment environment and keep your API keys secret.


9. Performance & Cost

ElevenLabs charges per character. With the free tier you get 5,000 characters per month, which is enough for a handful of headlines. For a production app:

  • Cache the audio files (e.g., in S3) to avoid repeated TTS calls.
  • Use a CDN to serve the MP3s quickly.
  • Monitor usage in the ElevenLabs dashboard.

10. Security Considerations

  • Rate limit your /read endpoint to prevent abuse.
  • Validate incoming text to avoid injection attacks.
  • Store API keys in a secrets manager, not in plain files.

11. Next Steps

  • Add pagination to fetch more headlines.
  • Implement a “continuous reading” mode that streams articles sequentially.
  • Integrate with voice assistants (Alexa, Google Assistant) for a hands‑free experience.
  • Explore emotion‑controlled voices from ElevenLabs to match the tone of the news.

Call to Action

You’ve now got a working prototype that turns headlines into speech, all powered by ElevenLabs’ high‑quality TTS. Ready to take your news app to the next level? Sign up and get started today—your ears (and your users’) will thank you.

Try ElevenLabs now: https://try.elevenlabs.io/kr07zfuqn1bp

Top comments (0)