How to Add Voice to Your React App with ElevenLabs
说明与用途
本指南展示了如何使用 ElevenLabs 在 React 应用中添加语音输出,使用 REST API、axios 和自定义 Hook。
问题
Integrate realistic text‑to‑speech into a React application.
结果
The workflow yields a functional React component that converts user‑typed text into spoken audio using ElevenLabs, with clear loading and error handling.
工作流
- Obtain an ElevenLabs API key via the sign‑up page and dashboard.
- Store the key in a .env file as REACT_APP_ELEVENLABS_API_KEY.
- Create a fresh React project (or use an existing one) and install axios.
- Add a service wrapper in src/api/elevenlabs.js that POSTs to /text-to-speech/{voiceId} and returns an object URL for the MP3 blob.
- Implement a custom hook src/hooks/useElevenLabs.js that manages loading, error, and audioUrl state and exposes a speak(text) function.
- Build a UI component that lets users type text and plays the returned audio URL via an
<audio>element. - Use the hook in the component to trigger synthesis and display loading/error feedback.
证据
ElevenLabs – a modern TTS platform that offers ultra‑realistic speech, custom voice cloning, and a straightforward REST API.
We POST the text to /text-to-speech/{voiceId}. The response is an MP3 blob; we turn it into an object URL so the browser can play it instantly.
The hook returns: speak(text): triggers synthesis; audioUrl: a temporary URL you can feed to an <audio> element.
- 记录日期: 2026-11-01T02:43:55.321Z