SDK 使用 #

概述 #

ElevenLabs 提供了官方的 Python 和 Node.js SDK,简化 API 调用和集成开发。

text
┌─────────────────────────────────────────────────────────────┐
│                    SDK 支持                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐         │
│  │   Python    │  │  Node.js    │  │   REST API  │         │
│  │    SDK      │  │    SDK      │  │   (通用)    │         │
│  └─────────────┘  └─────────────┘  └─────────────┘         │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Python SDK #

安装 #

bash
# 使用 pip
pip install elevenlabs

# 使用 poetry
poetry add elevenlabs

# 使用 pipenv
pipenv install elevenlabs

初始化 #

python
import os
from elevenlabs import ElevenLabs

# 方式一:直接传入 API Key
client = ElevenLabs(api_key="your_api_key")

# 方式二:使用环境变量
client = ElevenLabs()  # 自动读取 ELEVENLABS_API_KEY

# 方式三:异步客户端
from elevenlabs import AsyncElevenLabs
async_client = AsyncElevenLabs(api_key="your_api_key")

文本转语音 #

python
# 基础用法
audio = client.text_to_speech.convert(
    text="Hello, world!",
    voice_id="JBFqnCBsd6RMkjVDRZzb",
    model_id="eleven_multilingual_v2"
)

with open("output.mp3", "wb") as f:
    for chunk in audio:
        f.write(chunk)

# 流式输出
audio_stream = client.text_to_speech.convert_as_stream(
    text="Long text content...",
    voice_id="JBFqnCBsd6RMkjVDRZzb",
    model_id="eleven_multilingual_v2"
)

with open("output_stream.mp3", "wb") as f:
    for chunk in audio_stream:
        f.write(chunk)

# 自定义设置
audio = client.text_to_speech.convert(
    text="Custom voice settings",
    voice_id="JBFqnCBsd6RMkjVDRZzb",
    model_id="eleven_multilingual_v2",
    voice_settings={
        "stability": 0.3,
        "similarity_boost": 0.8,
        "style": 0.5,
        "use_speaker_boost": True
    },
    output_format="mp3_44100_192"
)

语音管理 #

python
# 获取所有语音
voices = client.voices.get_all()
for voice in voices.voices:
    print(f"{voice.name}: {voice.voice_id}")

# 获取单个语音
voice = client.voices.get(voice_id="voice_id")

# 克隆语音
voice = client.voices.clone(
    name="My Voice",
    files=["/path/to/audio.mp3"]
)

# 删除语音
client.voices.delete(voice_id="voice_id")

用户信息 #

python
# 获取用户信息
user = client.user.get()
print(f"Characters used: {user.subscription.character_count}")
print(f"Character limit: {user.subscription.character_limit}")

# 获取订阅信息
subscription = client.user.subscription.get()
print(f"Tier: {subscription.tier}")

历史记录 #

python
# 获取历史记录
history = client.history.get()
for item in history.history:
    print(f"{item.text[:50]}... - {item.state}")

# 下载历史音频
audio = client.history.get_audio(history_item_id="item_id")

异步操作 #

python
import asyncio
from elevenlabs import AsyncElevenLabs

async def generate_multiple():
    client = AsyncElevenLabs(api_key="your_api_key")
    
    texts = ["Text 1", "Text 2", "Text 3"]
    tasks = [
        client.text_to_speech.convert(
            text=text,
            voice_id="JBFqnCBsd6RMkjVDRZzb",
            model_id="eleven_multilingual_v2"
        )
        for text in texts
    ]
    
    results = await asyncio.gather(*tasks)
    return results

# 运行
results = asyncio.run(generate_multiple())

Node.js SDK #

安装 #

bash
# 使用 npm
npm install elevenlabs

# 使用 yarn
yarn add elevenlabs

# 使用 pnpm
pnpm add elevenlabs

初始化 #

typescript
import { ElevenLabsClient } from "elevenlabs";

// 方式一:直接传入 API Key
const client = new ElevenLabsClient({
  apiKey: "your_api_key",
});

// 方式二:使用环境变量
const client = new ElevenLabsClient(); // 自动读取 ELEVENLABS_API_KEY

文本转语音 #

typescript
// 基础用法
async function generateSpeech() {
  const audio = await client.textToSpeech.convert({
    text: "Hello, world!",
    voiceId: "JBFqnCBsd6RMkjVDRZzb",
    modelId: "eleven_multilingual_v2",
  });

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

  const buffer = Buffer.concat(chunks);
  return buffer;
}

// 流式输出
async function streamSpeech() {
  const audioStream = await client.textToSpeech.convertAsStream({
    text: "Long text content...",
    voiceId: "JBFqnCBsd6RMkjVDRZzb",
    modelId: "eleven_multilingual_v2",
  });

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

  return Buffer.concat(chunks);
}

// 自定义设置
async function customSettings() {
  const audio = await client.textToSpeech.convert({
    text: "Custom voice settings",
    voiceId: "JBFqnCBsd6RMkjVDRZzb",
    modelId: "eleven_multilingual_v2",
    voiceSettings: {
      stability: 0.3,
      similarityBoost: 0.8,
      style: 0.5,
      useSpeakerBoost: true,
    },
    outputFormat: "mp3_44100_192",
  });

  return audio;
}

语音管理 #

typescript
// 获取所有语音
async function listVoices() {
  const voices = await client.voices.getAll();
  voices.voices.forEach((voice) => {
    console.log(`${voice.name}: ${voice.voiceId}`);
  });
}

// 获取单个语音
async function getVoice(voiceId: string) {
  const voice = await client.voices.get(voiceId);
  return voice;
}

// 克隆语音
async function cloneVoice(name: string, files: string[]) {
  const voice = await client.voices.clone({
    name,
    files,
  });
  return voice;
}

// 删除语音
async function deleteVoice(voiceId: string) {
  await client.voices.delete(voiceId);
}

用户信息 #

typescript
// 获取用户信息
async function getUserInfo() {
  const user = await client.user.get();
  console.log(`Characters used: ${user.subscription.characterCount}`);
  console.log(`Character limit: ${user.subscription.characterLimit}`);
}

// 获取订阅信息
async function getSubscription() {
  const subscription = await client.user.subscription.get();
  console.log(`Tier: ${subscription.tier}`);
}

历史记录 #

typescript
// 获取历史记录
async function getHistory() {
  const history = await client.history.get();
  history.history.forEach((item) => {
    console.log(`${item.text.substring(0, 50)}... - ${item.state}`);
  });
}

// 下载历史音频
async function downloadHistoryAudio(itemId: string) {
  const audio = await client.history.getAudio(itemId);
  return audio;
}

错误处理 #

Python #

python
from elevenlabs import ElevenLabs, APIError, RateLimitError, AuthenticationError

try:
    audio = client.text_to_speech.convert(
        text="Hello",
        voice_id="invalid_id",
        model_id="eleven_multilingual_v2"
    )
except AuthenticationError as e:
    print(f"Authentication failed: {e}")
except RateLimitError as e:
    print(f"Rate limit exceeded: {e}")
    time.sleep(60)
except APIError as e:
    print(f"API error: {e}")

Node.js #

typescript
try {
  const audio = await client.textToSpeech.convert({
    text: "Hello",
    voiceId: "invalid_id",
    modelId: "eleven_multilingual_v2",
  });
} catch (error) {
  if (error.status === 401) {
    console.error("Authentication failed");
  } else if (error.status === 429) {
    console.error("Rate limit exceeded");
    await new Promise((resolve) => setTimeout(resolve, 60000));
  } else {
    console.error(`API error: ${error.message}`);
  }
}

类型定义 #

TypeScript 类型 #

typescript
interface VoiceSettings {
  stability: number;
  similarityBoost: number;
  style?: number;
  useSpeakerBoost?: boolean;
}

interface ConvertOptions {
  text: string;
  voiceId: string;
  modelId?: string;
  voiceSettings?: VoiceSettings;
  outputFormat?: string;
}

interface Voice {
  voiceId: string;
  name: string;
  category: string;
  labels?: Record<string, string>;
}

下一步 #

最后更新:2026-04-05