快速开始 #

准备工作 #

在开始之前,你需要准备以下内容:

text
┌─────────────────────────────────────────────────────────────┐
│                    准备清单                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ✅ 电子邮箱(用于注册账户)                                 │
│  ✅ Python 3.8+ 或 Node.js 18+                              │
│  ✅ 基本的编程知识                                           │
│  ✅ 网络连接                                                 │
│                                                             │
└─────────────────────────────────────────────────────────────┘

第一步:注册账户 #

1. 访问官网 #

text
打开浏览器,访问:
https://elevenlabs.io

点击右上角 "Sign Up" 按钮

2. 注册方式 #

text
┌─────────────────────────────────────────────────────────────┐
│                    注册选项                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  方式一:Google 账户登录                                     │
│  ├── 点击 "Continue with Google"                            │
│  └── 授权登录                                               │
│                                                             │
│  方式二:邮箱注册                                            │
│  ├── 输入邮箱地址                                           │
│  ├── 设置密码                                               │
│  └── 验证邮箱                                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

3. 完成注册 #

text
注册成功后:
├── 获得免费额度(每月 10,000 字符)
├── 访问 Web 界面
└── 获取 API Key

第二步:获取 API Key #

1. 进入设置页面 #

text
┌─────────────────────────────────────────────────────────────┐
│                    获取 API Key                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  步骤:                                                     │
│  1. 登录 ElevenLabs 账户                                    │
│  2. 点击右上角头像                                          │
│  3. 选择 "Profile Settings"                                 │
│  4. 找到 "API Key" 部分                                     │
│  5. 点击 "Create API Key"                                   │
│                                                             │
└─────────────────────────────────────────────────────────────┘

2. 创建并保存 API Key #

text
重要提示:
┌─────────────────────────────────────────────────────────────┐
│                                                             │
│  ⚠️ API Key 只显示一次,请立即保存                          │
│                                                             │
│  安全建议:                                                  │
│  ├── 不要硬编码在代码中                                     │
│  ├── 使用环境变量存储                                       │
│  ├── 不要提交到版本控制                                     │
│  └── 定期轮换 API Key                                       │
│                                                             │
└─────────────────────────────────────────────────────────────┘

3. 配置环境变量 #

bash
# Linux/macOS
export ELEVENLABS_API_KEY="your_api_key_here"

# Windows (PowerShell)
$env:ELEVENLABS_API_KEY="your_api_key_here"

# 或添加到配置文件
# ~/.bashrc 或 ~/.zshrc
echo 'export ELEVENLABS_API_KEY="your_api_key_here"' >> ~/.zshrc

第三步:安装 SDK #

Python 安装 #

bash
# 使用 pip 安装
pip install elevenlabs

# 或使用 poetry
poetry add elevenlabs

Node.js 安装 #

bash
# 使用 npm
npm install elevenlabs

# 或使用 yarn
yarn add elevenlabs

# 或使用 pnpm
pnpm add elevenlabs

第四步:第一个语音合成 #

Python 示例 #

python
import os
from elevenlabs import ElevenLabs

# 初始化客户端
client = ElevenLabs(
    api_key=os.getenv("ELEVENLABS_API_KEY")
)

# 文本转语音
text = "你好,欢迎使用 ElevenLabs AI 语音服务!"

# 调用 API
audio = client.text_to_speech.convert(
    text=text,
    voice_id="JBFqnCBsd6RMkjVDRZzb",  # Rachel 语音
    model_id="eleven_multilingual_v2",
    output_format="mp3_44100_128"
)

# 保存音频文件
with open("output.mp3", "wb") as f:
    for chunk in audio:
        f.write(chunk)

print("音频已保存到 output.mp3")

Node.js 示例 #

javascript
import { ElevenLabsClient } from "elevenlabs";
import { writeFileSync } from "fs";

const client = new ElevenLabsClient({
  apiKey: process.env.ELEVENLABS_API_KEY,
});

async function generateSpeech() {
  const text = "你好,欢迎使用 ElevenLabs AI 语音服务!";

  const audio = await client.textToSpeech.convert({
    text: text,
    voiceId: "JBFqnCBsd6RMkjVDRZzb",
    modelId: "eleven_multilingual_v2",
    outputFormat: "mp3_44100_128",
  });

  const chunks = [];
  for await (const chunk of audio) {
    chunks.push(chunk);
  }

  const buffer = Buffer.concat(chunks);
  writeFileSync("output.mp3", buffer);

  console.log("音频已保存到 output.mp3");
}

generateSpeech();

使用 REST API #

bash
curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/JBFqnCBsd6RMkjVDRZzb" \
  -H "xi-api-key: your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "你好,欢迎使用 ElevenLabs AI 语音服务!",
    "model_id": "eleven_multilingual_v2",
    "voice_settings": {
      "stability": 0.5,
      "similarity_boost": 0.75
    }
  }' \
  --output output.mp3

第五步:运行并验证 #

运行代码 #

bash
# Python
python your_script.py

# Node.js
node your_script.js

验证输出 #

text
┌─────────────────────────────────────────────────────────────┐
│                    验证步骤                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. 检查是否生成了 output.mp3 文件                           │
│  2. 使用音频播放器打开文件                                   │
│  3. 确认语音质量和内容                                       │
│                                                             │
│  预期结果:                                                  │
│  ✅ 文件成功生成                                             │
│  ✅ 语音清晰自然                                             │
│  ✅ 内容与输入文本一致                                       │
│                                                             │
└─────────────────────────────────────────────────────────────┘

常用语音 ID #

预置语音列表 #

text
┌─────────────────────────────────────────────────────────────┐
│                    推荐预置语音                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  Rachel (JBFqnCBsd6RMkjVDRZzb)                               │
│  ├── 女性,美式英语                                         │
│  └── 温暖、专业                                             │
│                                                             │
│  Domi (AZnzlk1XvdvUeBn1ldMn)                                 │
│  ├── 男性,美式英语                                         │
│  └── 深沉、有力                                             │
│                                                             │
│  Bella (EXAVITQu4vr4xnSDxMaL)                                │
│  ├── 女性,美式英语                                         │
│  └── 柔和、友好                                             │
│                                                             │
│  Antoni (ErXwLH5i43ZdrnRw6Rgd)                               │
│  ├── 男性,美式英语                                         │
│  └── 清晰、稳重                                             │
│                                                             │
│  Elli (MF3mGyEYCl7XYWbV9V6O)                                 │
│  ├── 女性,美式英语                                         │
│  └── 年轻、活力                                             │
│                                                             │
│  Josh (TxGEqnHWrfWFTfGW9XjX)                                 │
│  ├── 男性,美式英语                                         │
│  └── 成熟、可靠                                             │
│                                                             │
└─────────────────────────────────────────────────────────────┘

获取完整语音列表 #

python
# Python
voices = client.voices.get_all()
for voice in voices.voices:
    print(f"{voice.name}: {voice.voice_id}")
javascript
// Node.js
const voices = await client.voices.getAll();
voices.voices.forEach((voice) => {
  console.log(`${voice.name}: ${voice.voiceId}`);
});

进阶示例 #

自定义语音设置 #

python
audio = client.text_to_speech.convert(
    text="这是一段带有情感变化的文本",
    voice_id="JBFqnCBsd6RMkjVDRZzb",
    model_id="eleven_multilingual_v2",
    voice_settings={
        "stability": 0.3,          # 更有表现力
        "similarity_boost": 0.8,   # 更高相似度
        "style": 0.5,              # 增加风格
        "use_speaker_boost": True  # 说话者增强
    }
)

流式输出 #

python
# 流式生成,适合长文本
audio_stream = client.text_to_speech.convert_as_stream(
    text="这是一段很长的文本..." * 100,
    voice_id="JBFqnCBsd6RMkjVDRZzb",
    model_id="eleven_multilingual_v2"
)

with open("output_stream.mp3", "wb") as f:
    for chunk in audio_stream:
        f.write(chunk)
        print(f"已接收 {len(chunk)} 字节")

错误处理 #

常见错误 #

text
┌─────────────────────────────────────────────────────────────┐
│                    常见错误及解决方案                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  401 Unauthorized                                           │
│  ├── 原因:API Key 无效或过期                               │
│  └── 解决:检查并更新 API Key                               │
│                                                             │
│  429 Too Many Requests                                      │
│  ├── 原因:超过速率限制                                     │
│  └── 解决:等待后重试,或升级账户                           │
│                                                             │
│  400 Bad Request                                            │
│  ├── 原因:参数错误                                         │
│  └── 解决:检查请求参数格式                                 │
│                                                             │
│  422 Unprocessable Entity                                   │
│  ├── 原因:文本内容违规                                     │
│  └── 解决:修改文本内容                                     │
│                                                             │
└─────────────────────────────────────────────────────────────┘

错误处理示例 #

python
from elevenlabs import ElevenLabs, APIError, RateLimitError

try:
    audio = client.text_to_speech.convert(
        text="Hello",
        voice_id="invalid_id",
        model_id="eleven_multilingual_v2"
    )
except RateLimitError as e:
    print(f"速率限制: {e}")
    # 等待后重试
except APIError as e:
    print(f"API 错误: {e}")
except Exception as e:
    print(f"未知错误: {e}")

下一步 #

恭喜你完成了第一个 ElevenLabs 项目!接下来可以学习:

最后更新:2026-04-05