ElevenLabs + React: Building a Voice-Enabled UI
Why Voice AI Matters in Modern Apps Voice is the newest frontier of human‑computer interaction. Whether you’re building a smart home dashboard, a learning platform, or an accessibility��first product, adding spoken out
Why Voice AI Matters in Modern Apps
Voice is the newest frontier of human‑computer interaction. Whether you’re building a smart home dashboard, a learning platform, or an accessibility��first product, adding spoken output can:
- Reduce friction – users can consume content hands‑free.
- Improve accessibility – people with visual or motor impairments benefit from audio narration.
- Boost engagement – spoken UI feels more natural and can keep users on your app longer.
If you’re a React developer looking to add text‑to‑speech (TTS) or voice cloning, the key question is: Which service gives you high‑quality, developer‑friendly APIs? In this post, we’ll walk through setting up a simple React UI that talks back to you using ElevenLabs, a leading voice AI platform that offers realistic, customizable voices and a straightforward REST API.
Choosing ElevenLabs for Voice Generation
ElevenLabs has become the go‑to for many developers because of:
- High‑fidelity, human‑like voices that work across languages.
- Easy voice cloning – upload a short audio sample and generate a unique voice model in minutes.
- Rich API – supports streaming audio, SSML, and custom voice parameters.
- Developer‑friendly pricing – pay per usage, with a generous free tier.
If you’re curious, you can sign up and start experimenting right away: https://try.elevenlabs.io/kr07zfuqn1bp.
Prerequisites
- Node.js (v18+) and npm or yarn
- Basic familiarity with React (create‑react‑app or Vite)
- An ElevenLabs API key (obtainable from the signup link above)
Project Skeleton
Create a fresh React app:
npx create-react-app voice-ui
cd voice-ui
npm install axios
We’ll use axios for HTTP requests and react‑audio-player for playing back the generated audio.
npm install react-audio-player
Building the UI
Let’s design a minimal UI:
- Text input – where users type the message.
- Voice selector – choose a voice from ElevenLabs.
- Generate button – triggers TTS.
- Audio player – plays the result.
Here’s a simple component layout:
// src/components/VoiceTTS.tsx
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import AudioPlayer from 'react-audio-player';
const VoiceTTS: React.FC = () => {
const [text, setText] = useState('');
const [voices, setVoices] = useState<any[]>([]);
const [selectedVoice, setSelectedVoice] = useState('');
const [audioUrl, setAudioUrl] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const apiKey = process.env.REACT_APP_ELEVENLABS_API_KEY;
// Fetch available voices on mount
useEffect(() => {
axios
.get('https://api.elevenlabs.io/v1/voices', {
headers: { Authorization: apiKey },
})
.then((res) => setVoices(res.data.voices))
.catch(console.error);
}, [apiKey]);
const generateSpeech = async () => {
setLoading(true);
try {
const response = await axios.post(
'https://api.elevenlabs.io/v1/text-to-speech',
{
text,
voice_id: selectedVoice,
model_id: 'eleven_monolingual_v1',
output_format: 'mp3',
},
{
headers: {
Authorization: apiKey,
'Content-Type': 'application/json',
},
responseType: 'blob',
}
);
const audioBlob = new Blob([response.data], { type: 'audio/mpeg' });
const url = URL.createObjectURL(audioBlob);
setAudioUrl(url);
} catch (err) {
console.error(err);
alert('Failed to generate speech. Check console for details.');
} finally {
setLoading(false);
}
};
return (
<div style={{ maxWidth: 600, margin: 'auto' }}>
<h2>Voice‑Enabled UI</h2>
<textarea
rows={4}
placeholder="Type something to speak…"
value={text}
onChange={(e) => setText(e.target.value)}
style={{ width: '100%', padding: 8 }}
/>
<select
value={selectedVoice}
onChange={(e) => setSelectedVoice(e.target.value)}
style={{ marginTop: 12, width: '100%', padding: 8 }}
>
<option value="" disabled>
Select a voice
</option>
{voices.map((v) => (
<option key={v.voice_id} value={v.voice_id}>
{v.name} ({v.language_name})
</option>
))}
</select>
<button
onClick={generateSpeech}
disabled={!text || !selectedVoice || loading}
style={{
marginTop: 12,
padding: '8px 16px',
cursor: loading ? 'not-allowed' : 'pointer',
}}
>
{loading ? 'Generating…' : 'Speak'}
</button>
{audioUrl && (
<AudioPlayer
src={audioUrl}
controls
style={{ marginTop: 20, width: '100%' }}
/>
)}
</div>
);
};
export default VoiceTTS;
Add this component to your App.tsx (or App.jsx if you’re not using TypeScript). Don’t forget to set the REACT_APP_ELEVENLABS_API_KEY in a .env file.
# .env
REACT_APP_ELEVENLABS_API_KEY=your_api_key_here
Now run the app:
npm start
You should see a simple UI where you can type text, pick a voice, and hear the spoken output. 🎤
Voice Cloning Demo
ElevenLabs also offers a voice cloning feature. Let’s walk through how to create a custom voice with just a short audio clip.
- Prepare a 5–10 second sample (preferably clear speech).
- Upload the sample using the API.
Here’s a quick curl example to create a new voice:
curl -X POST https://api.elevenlabs.io/v1/voices \
-H "Content-Type: application/json" \
-H "xi-api-key: YOUR_API_KEY" \
-d '{
"name": "Custom Voice",
"sample_file": "file://path/to/your/sample.wav",
"sample_text": "Hello, this is a test."
}'
The response will contain a voice_id you can use in your React app just like any other voice. The cloning process is quick and the resulting voice is remarkably natural.
Handling Audio Streaming
For larger texts or real‑time applications, you might want to stream audio chunks instead of waiting for the entire file. ElevenLabs’ API supports streaming via WebSocket or multipart responses. In a React context, you can:
- Use the
ReadableStreamAPI to progressively decode audio. - Play chunks as they arrive with the Web Audio API.
- Provide a “Stop” button to abort the stream.
While the example above downloads the full MP3, streaming can reduce latency and improve user experience for long messages.
Performance Tips
- Cache generated audio: Store the MP3 URL in a cache (localStorage, IndexedDB, or a CDN) keyed by a hash of the text and voice. This avoids redundant API calls.
- Debounce input: If you plan to auto‑generate speech on every keystroke, debounce the request to reduce load.
- Batch requests: For multi‑page apps, pre‑fetch popular voices or sample audios during idle time.
Security Considerations
- Never expose your ElevenLabs API key on the client. Keep it in server‑side code or use a Cloud Function to proxy requests.
- If you expose a proxy, validate the
textinput to avoid injection attacks or abuse.
Wrap‑Up
You’ve now:
- Set up a React UI that turns typed text into spoken words.
- Integrated ElevenLabs’ powerful TTS API.
- Learned how to clone a custom voice in minutes.
- Got tips for performance and security.
Voice AI is no longer a niche feature—it's becoming essential for accessible, engaging, and modern user experiences. With ElevenLabs, you can focus on building the UI while the platform handles the heavy lifting of generating lifelike speech.
Ready to make your app talk?
If you haven’t tried ElevenLabs yet, sign up today and get a taste of their realistic voices: https://try.elevenlabs.io/kr07zfuqn1bp. Happy coding—and happy listening!
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.