DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

How to Add Voice to Your React App with ElevenLabs

Why Add Voice to Your React App?

Modern users expect more than static text. Voice can make your app more accessible, engaging, and memorable. Whether you’re building a language learning tool, a virtual assistant, or a storytelling platform, integrating text‑to‑speech (TTS) lets your content come alive without writing a single line of code for voice synthesis.

When it comes to TTS and voice cloning, the market is crowded with options, but a few stand out for their ease of use, quality, and developer‑friendly APIs. In this post we’ll show you how to add high‑fidelity voice to a React app using ElevenLabs (link: https://try.elevenlabs.io/kr07zfuqn1bp). We’ll walk through API setup, sample code, and a quick demo of voice cloning—all in under an hour.

Getting Started with ElevenLabs

ElevenLabs offers a powerful, cloud‑based TTS engine that supports:

  • Multiple natural voices (male, female, children, accents)
  • Voice cloning from a few minutes of audio
  • Real‑time streaming via WebSocket
  • RESTful API with simple JSON payloads

1. Sign Up & Grab an API Key

  1. Visit the affiliate link above to sign up: https://try.elevenlabs.io/kr07zfuqn1bp
  2. After registration, navigate to the API Keys section in the dashboard.
  3. Copy the key—keep it secret. We’ll use it in our React app.

Tip: Store the key in an .env file and reference it with process.env.REACT_APP_ELEVENLABS_API_KEY. Never commit the file to version control.

2. Install Dependencies

# Create a new React app if you don’t have one
npx create-react-app voice-demo
cd voice-demo

# Install Axios for HTTP requests
npm install axios
Enter fullscreen mode Exit fullscreen mode

Making a Simple TTS Request

Let’s start with a vanilla TTS request. ElevenLabs expects a POST to /v1/text-to-speech/{voice_id} with a JSON body.

// src/services/elevenLabs.js
import axios from 'axios';

const API_KEY = process.env.REACT_APP_ELEVENLABS_API_KEY;
const BASE_URL = 'https://api.elevenlabs.io/v1';

export const synthesizeSpeech = async (voiceId, text) => {
  const response = await axios.post(
    `${BASE_URL}/text-to-speech/${voiceId}`,
    {
      text,
      voice_settings: {
        stability: 0.5,
        similarity_boost: 0.75
      }
    },
    {
      headers: {
        Accept: 'audio/mpeg',
        'xi-api-key': API_KEY
      },
      responseType: 'blob' // important for binary data
    }
  );
  return URL.createObjectURL(response.data);
};
Enter fullscreen mode Exit fullscreen mode

Using the Service in a Component

// src/App.js
import React, { useState } from 'react';
import { synthesizeSpeech } from './services/elevenLabs';

function App() {
  const [text, setText] = useState('Hello, world!');
  const [audioUrl, setAudioUrl] = useState(null);

  const handleSpeak = async () => {
    // Replace with an actual voice ID from your dashboard
    const voiceId = 'EXAVITQu4vr4xnSDxMaL';
    const url = await synthesizeSpeech(voiceId, text);
    setAudioUrl(url);
  };

  return (
    <div style={{ padding: '2rem' }}>
      <h1>React Voice Demo</h1>
      <textarea
        value={text}
        onChange={(e) => setText(e.target.value)}
        rows={4}
        cols={50}
      />
      <br />
      <button onClick={handleSpeak}>Speak</button>

      {audioUrl && (
        <audio controls src={audioUrl} style={{ marginTop: '1rem' }} />
      )}
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Run the app (npm start) and you should hear your text read aloud. Feel free to experiment with the voice settings to tweak the sound.

Going Beyond: Voice Cloning

One of ElevenLabs’ most exciting features is voice cloning—creating a synthetic voice that sounds like a real person from just a few minutes of audio. This opens doors for personalized assistants, brand mascots, and more.

1. Upload a Sample Audio

ElevenLabs requires a short audio clip (min 10 s, max 2 min). Upload it through the dashboard or programmatically:

curl -X POST https://api.elevenlabs.io/v1/voices \
  -H "xi-api-key: YOUR_API_KEY" \
  -F "audio=@/path/to/your/sample.wav"
Enter fullscreen mode Exit fullscreen mode

You’ll receive a voice_id in the response—use it in the next step.

2. Create a Custom Voice

curl -X POST https://api.elevenlabs.io/v1/custom-voices \
  -H "xi-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
        "name": "My Custom Voice",
        "description": "Clone of my own voice",
        "audio": "BASE64_ENCODED_AUDIO"
      }'
Enter fullscreen mode Exit fullscreen mode

Note: The API expects the audio in base64. Use a small script to convert your WAV file if needed.

3. Use the Cloned Voice in Your App

Replace the voiceId in the synthesizeSpeech call with your custom voice ID. The rest of the code stays the same.

Streaming Audio in Real Time

For applications that require low latency (e.g., a live chatbot), ElevenLabs supports WebSocket streaming. The SDK handles reconnections, but here’s a minimal example:

const socket = new WebSocket('wss://api.elevenlabs.io/v1/speech-stream');
socket.addEventListener('open', () => {
  socket.send(JSON.stringify({
    voice_id: 'YOUR_VOICE_ID',
    text: 'Streaming example text...',
    // Optional: stream settings
  }));
});

const chunks = [];
socket.addEventListener('message', (event) => {
  chunks.push(event.data);
});

socket.addEventListener('close', () => {
  const blob = new Blob(chunks, { type: 'audio/mpeg' });
  const url = URL.createObjectURL(blob);
  const audio = new Audio(url);
  audio.play();
});
Enter fullscreen mode Exit fullscreen mode

Handling Edge Cases and Security

  • Rate Limits: ElevenLabs imposes per‑minute and per‑hour limits. Monitor your usage in the dashboard.
  • CORS: All API calls are CORS‑enabled, but keep your key in environment variables.
  • Error Handling: Wrap your calls in try/catch blocks and show user‑friendly messages.
try {
  const url = await synthesizeSpeech(voiceId, text);
  setAudioUrl(url);
} catch (err) {
  console.error('Speech synthesis failed', err);
  alert('Oops! Something went wrong. Please try again later.');
}
Enter fullscreen mode Exit fullscreen mode

Building a Polished UI

Once you have the core functionality, polish your app:

  • Voice Selector: Let users choose from available voices via a dropdown.
  • Speed & Pitch Controls: Expose voice_settings to tweak speaking rate and intonation.
  • Download Option: Offer a button to download the generated MP3.
  • Accessibility: Provide captions or transcripts for users who prefer text.

Recap & Next Steps

  1. Sign up at https://try.elevenlabs.io/kr07zfuqn1bp and grab your API key.
  2. Integrate the simple TTS function into your React app.
  3. Clone a voice if you want a personalized touch.
  4. Stream audio for real‑time applications.
  5. Enhance your UI and handle edge cases.

ElevenLabs’ combination of high‑quality voices, fast API, and straightforward SDKs makes it a top choice for developers looking to add voice to their apps. Whether you’re building a chatbot, an e‑learning platform, or a creative storytelling tool, you can bring your content to life in minutes.

Call to Action

Ready to give your React app a voice? Sign up today through the affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp, grab your API key, and start building voice‑enabled experiences that users will love. Happy coding!

Top comments (0)