跳到正文
DEV Community· VoiceDeveloper·· 2 小時前AI 評分39

ElevenLabs 如何為 React 應用加入語音

How to Add Voice to Your React App with ElevenLabs

AI 導讀

ElevenLabs 可透過伺服器端 Node.js 代理接入 React 應用,將文字送至 API,再把串流 MP3 音訊傳回瀏覽器播放。文章示範建立可重用的語音按鈕,並説明如何避免在瀏覽器暴露 API key,以及選用語音複製功能。

正文

Why Add Voice to Your React App?

Voice is the next big UI layer. Whether you’re building an accessibility‑first dashboard, a language‑learning tool, or a chatbot that feels human, a smooth text‑to‑speech (TTS) experience can turn a static page into an interactive conversation. Modern TTS services can generate natural‑sounding speech in milliseconds, and with voice‑cloning you can even give your product a unique “brand voice”.

In this guide we’ll walk through wiring up ElevenLabs – a leading AI voice platform – to a React front‑end. By the end you’ll have a reusable <VoiceButton> component that sends text to the ElevenLabs API, streams back audio, and plays it back in the browser.

Quick note: All the code below assumes you’re using a recent version of React (≥18) and have a Vite or Create‑React‑App setup.


1. Get an ElevenLabs API Key

  1. Sign up (or log in) at the ElevenLabs platform.
  2. Navigate to API Keys in your dashboard.
  3. Copy the generated key – you’ll need it for the server‑side proxy we’ll create next.

👉 If you haven’t signed up yet, you can start with the affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp


2. Why a Proxy?

ElevenLabs requires the API key to be sent in an Authorization: Bearer … header. Exposing that key in the browser would be a security risk, so we’ll create a tiny Node.js endpoint that forwards the request. This also lets us keep the request body small (the service supports streaming responses).


3. Setting Up the Backend Proxy

Create a folder called server at the root of your project and add a simple Express server.

mkdir server && cd server
npm init -y
npm install express cors node-fetch dotenv

Create a .env file (add it to .gitignore) with:

ELEVENLABS_API_KEY=your_elevenlabs_api_key_here

Now index.js:

// server/index.js
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const fetch = require('node-fetch');

const app = express();
app.use(cors());
app.use(express.json());

const ELEVEN_API = 'https://api.elevenlabs.io/v1';

app.post('/api/tts', async (req, res) => {
  const { text, voiceId = 'EXAVITQu4vr4xnSDxMaL' } = req.body; // default voice

  try {
    const response = await fetch(`${ELEVEN_API}/text-to-speech/${voiceId}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'xi-api-key': process.env.ELEVENLABS_API_KEY,
        // Use streaming response
        Accept: 'audio/mpeg',
      },
      body: JSON.stringify({
        text,
        model_id: 'eleven_monolingual_v1',
        voice_settings: { stability: 0.5, similarity_boost: 0.75 },
      }),
    });

    if (!response.ok) {
      const err = await response.text();
      return res.status(response.status).send(err);
    }

    // Pipe the audio stream straight back to the client
    res.setHeader('Content-Type', 'audio/mpeg');
    response.body.pipe(res);
  } catch (e) {
    console.error(e);
    res.status(500).send('Server error');
  }
});

const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`Proxy running on http://localhost:${PORT}`));

Run it with:

node server/index.js

Your proxy is now listening on http://localhost:4000/api/tts.


4. Front‑End: The VoiceButton Component

Now let’s build a React component that talks to the proxy, receives the audio stream, and plays it.

// src/components/VoiceButton.tsx
import React, { useState, useRef } from 'react';

type VoiceButtonProps = {
  text: string;
  label?: string;
};

export const VoiceButton: React.FC<VoiceButtonProps> = ({
  text,
  label = '🔊 Speak',
}) => {
  const [loading, setLoading] = useState(false);
  const audioRef = useRef<HTMLAudioElement>(null);

  const handleClick = async () => {
    setLoading(true);
    try {
      const resp = await fetch('http://localhost:4000/api/tts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text }),
      });

      if (!resp.ok) throw new Error('TTS failed');

      // Convert the streamed response to a Blob URL
      const blob = await resp.blob();
      const url = URL.createObjectURL(blob);
      if (audioRef.current) {
        audioRef.current.src = url;
        audioRef.current.play();
      }
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <button onClick={handleClick} disabled={loading}>
        {loading ? '🔄 Generating…' : label}
      </button>
      {/* Hidden audio element */}
      <audio ref={audioRef} style={{ display: 'none' }} />
    </div>
  );
};

How it works

  1. The button triggers a POST to our /api/tts endpoint with the desired text.
  2. The backend streams back an MP3 file.
  3. We turn the response into a Blob, create an object URL, and hand it to an <audio> element for playback.

You can now drop <VoiceButton text="Hello, world!" /> anywhere in your UI.


5. Adding Voice Cloning (Optional)

ElevenLabs lets you upload a short sample (≈10 seconds) and generate a custom voice ID. Once you have a voiceId, pass it to the proxy:

// In server/index.js, modify the endpoint:
const { text, voiceId } = req.body; // now required from client
// ... then use voiceId in the fetch URL

On the front‑end:

<VoiceButton text="Welcome back!" voiceId="myCustomVoice123" />

The same component works; you only need to expose the voiceId prop.

For more details on voice cloning, check ElevenLabs documentation: https://try.elevenlabs.io/kr07zfuqn1bp


6. Handling Errors & Edge Cases

  • Network hiccups: Wrap the fetch call in a try/catch and surface a toast or inline message.
  • Large texts: ElevenLabs caps input length (~5 k characters). Split long paragraphs into chunks and queue them client‑side.
  • Browser compatibility: The audio/mpeg MIME type works in all modern browsers, but older Safari versions may need an audio/mp3 fallback.

7. Testing the Flow

Run both servers:

# Terminal 1
npm start          # your React dev server (usually http://localhost:5173)

# Terminal 2
node server/index.js

Open the app, click the button, and listen to the AI‑generated voice. You should hear near‑human speech within a second or two, depending on your connection.


8. Going Production

When you’re ready to ship:

  1. Deploy the proxy to a serverless platform (Vercel, Netlify Functions, or AWS Lambda).
  2. Store the API key in the platform’s secret manager – never bundle it with the front‑end bundle.
  3. Switch the fetch URL to the live endpoint, e.g., https://my‑tts‑proxy.vercel.app/api/tts.

Performance‑wise, ElevenLabs streams audio, so you can start playback before the entire file downloads – perfect for real‑time interactions.


9. Wrap‑Up

Adding voice to a React app used to be a multi‑step, expensive process involving heavyweight SDKs. With ElevenLabs, you get:

  • High‑quality, low‑latency speech (multiple languages, expressive tones).
  • Voice cloning to give your product a signature sound.
  • Simple REST API that works nicely with any front‑end framework.

All you need is a few lines of JavaScript, a tiny proxy, and you’re ready to let your UI talk.


Ready to give your users a voice?

Start experimenting today with ElevenLabs and see how natural‑sounding speech can elevate your React projects. Grab your API key and try it out now: https://try.elevenlabs.io/kr07zfuqn1bp

Happy coding! 🚀

來源:DEV Community · dev.to