@deepdub/node

中文文档
3.0.2发布于 2026/06/29ISCTypeScriptCommonJS近 30 天下载 4848

Deepdub API SDK

原始使用文档
文档目录31 节
  1. Installation
  2. Initialization
  3. Constructor parameters
  4. Protocol comparison
  5. Region endpoints
  6. Connection
  7. connect() — Open a WebSocket connection
  8. asyncConnect() — Alias for connect()
  9. disconnect() — Close the WebSocket connection
  10. Text-to-Speech
  11. tts() — Synchronous generation
  12. Full example with all common TTS parameters
  13. Voice cloning from audio reference
  14. ttsRetro() — Retroactive generation
  15. WebSocket TTS
  16. generateToBuffer() — Generate to buffer
  17. generateToFile() — Generate to file
  18. generateTo() — Low-level generation helper
  19. Streaming chunks
  20. Headerless chunks
  21. asyncTts() — Streaming generation
  22. Streaming Input
  23. Concurrent generations
  24. Voice Management
  25. listVoices() — List all voice prompts
  26. addVoice() — Upload a voice sample
  27. CLI Reference
  28. Environment Variables
  29. Error Handling
  30. Available Models
  31. Tests

Deepdub Node.js SDK

Install and use the Deepdub Node.js SDK for text-to-speech generation with streaming support.

Installation

npm install --save @deepdub/node
# or
yarn add @deepdub/node

Requirements: Node.js 18+ (uses native fetch)

Initialization

const { DeepdubClient } = require('@deepdub/node');

// Option 1: Pass API key directly
const deepdub = new DeepdubClient('dd-your-api-key');

// Option 2: Use DEEPDUB_API_KEY environment variable
require('dotenv').config();
const deepdubFromEnv = new DeepdubClient();

// HTTP protocol supports voiceReference and sampleRate with all formats
const deepdubHttp = new DeepdubClient('dd-your-api-key', { protocol: 'http' });

Constructor parameters

ParameterTypeDefaultDescription
apiKeystringprocess.env.DEEPDUB_API_KEYYour Deepdub API key. Falls back to DEEPDUB_API_KEY if not provided.
options.protocol'websocket' | 'http''websocket'Transport protocol: "websocket" for real-time streaming, or "http" for REST API.
options.baseUrlstringUS/EU REST URLBase URL for the REST API. Falls back to DEEPDUB_BASE_URL.
options.baseWebsocketUrlstringUS/EU WebSocket URLBase URL for the WebSocket API. Falls back to DEEPDUB_BASE_WEBSOCKET_URL.
options.baseWebsocketStreamingUrlstringwss://wss.deepdub.ai/wsBase URL for the WebSocket streaming API. Falls back to DEEPDUB_BASE_WEBSOCKET_STREAMING_URL.
options.eubooleanfalseUse EU region endpoints. Falls back to DD_EU=1.

Protocol comparison

FeatureWebSocketHTTP
Streaming chunks (onChunk)YesNo
sampleRate optionmp3 onlyAll formats
voiceReference optionNoYes
Concurrent generationsYesYes

Use WebSocket (default) for real-time streaming and low-latency playback. Use HTTP when you need voiceReference for instant voice cloning or sampleRate with non-mp3 formats.

Region endpoints

RegionREST APIWebSocket API
US (default)https://restapi.deepdub.ai/api/v1wss://wsapi.deepdub.ai/open
EUhttps://restapi.eu.deepdub.ai/api/v1wss://wsapi.eu.deepdub.ai/open

Enable EU with { eu: true } or DD_EU=1.

Connection

For WebSocket protocol, call connect() before using generateToBuffer(), generateToFile(), or generateTo(). For incremental text streaming, call asyncStreamConnect(). For HTTP protocol and REST methods, no connection step is needed.

connect() — Open a WebSocket connection

const deepdub = new DeepdubClient('dd-your-api-key');
await deepdub.connect();

Returns: Promise<WebSocket> — the opened WebSocket connection.

Parameters

No parameters.

asyncConnect() — Alias for connect()

await deepdub.asyncConnect();

Returns: Promise<WebSocket> — the opened WebSocket connection.

Parameters

No parameters.

disconnect() — Close the WebSocket connection

await deepdub.connect();

// ...generate audio...

deepdub.disconnect();

Call disconnect() when you are done with the WebSocket. If you skip it, the open connection keeps the Node.js process alive.

Returns: void

Parameters

No parameters.

Text-to-Speech

tts() — Synchronous generation

Generate speech and receive the complete audio as a Buffer.

const fs = require('fs');

const audio = await deepdub.tts('Hello, welcome to Deepdub!', {
  voicePromptId: 'your-voice-id',
  model: 'dd-etts-3.2',
  locale: 'en-US',
  format: 'mp3',
});

fs.writeFileSync('output.mp3', audio);

Returns: Promise<Buffer> — binary audio data in the specified format.

Parameters

ParameterTypeDefaultDescription
textstringRequiredText to convert to speech.
params.voicePromptIdstring—Voice prompt ID to use. Either this or voiceReference must be provided.
params.voiceReferencestring | Buffer—Audio reference for instant voice cloning. Accepts a file path, raw Buffer, or base64-encoded string. Either this or voicePromptId must be provided.
params.modelstringdd-etts-3.2Model ID.
params.localestringen-USLanguage locale code (e.g. en-US, fr-FR).
params.formatstringmp3Audio output format. REST supports mp3, opus, and mulaw.
params.temperaturenumber—Generation temperature (0.0-1.0). Higher values produce more varied output.
params.variancenumber—Voice variation level (0.0-1.0).
params.durationnumber—Target audio duration in seconds. Mutually exclusive with tempo.
params.temponumber—Playback speed multiplier. Mutually exclusive with duration.
params.seednumber—Random seed for deterministic generation.
params.promptBoostboolean—Enhance voice prompt characteristics.
params.sampleRatenumber—Output sample rate in Hz. Supported: 8000, 16000, 22050, 24000, 44100, 48000.
params.accentBaseLocalestring—Base accent locale. Must be provided together with accentLocale and accentRatio.
params.accentLocalestring—Target accent locale. Must be provided together with accentBaseLocale and accentRatio.
params.accentRationumber—Accent blend ratio (0.0-1.0). Must be provided together with accentBaseLocale and accentLocale.
params.accentControlobject—Accent blending object: { accentBaseLocale, accentLocale, accentRatio }.
params.targetGenderstring—Target gender for the output voice.
params.generationIdstringAuto-generated UUIDOptional UUID for request tracking.
params.superStretchboolean—Enable super stretch for longer audio.
params.realtimeboolean—Enable real-time priority processing.
params.cleanAudioboolean—Request audio cleanup when supported by the API.
params.autoGainboolean—Request automatic gain control when supported by the API.
params.publishboolean—Publish the generated asset when supported by the API.
params.performanceReferencePromptIdstring—Voice prompt ID to use as a performance reference.

Full example with all common TTS parameters

const audio = await deepdub.tts('This demonstrates common TTS parameters.', {
  voicePromptId: 'your-voice-id',
  model: 'dd-etts-3.2',
  locale: 'en-US',
  format: 'mp3',
  temperature: 0.7,
  variance: 0.6,
  tempo: 1.1,
  seed: 42,
  promptBoost: true,
  sampleRate: 44100,
  accentBaseLocale: 'en-US',
  accentLocale: 'fr-FR',
  accentRatio: 0.3,
});

require('fs').writeFileSync('output.mp3', audio);

Voice cloning from audio reference

const audio = await deepdub.tts('Cloning a voice from an audio sample.', {
  voiceReference: './reference_audio.mp3',
  model: 'dd-etts-3.2',
  locale: 'en-US',
});

require('fs').writeFileSync('cloned_output.mp3', audio);

ttsRetro() — Retroactive generation

Submit a TTS request and receive a URL for later retrieval.

const response = await deepdub.ttsRetro('Generate this audio for later retrieval.', {
  voicePromptId: 'your-voice-id',
  model: 'dd-etts-3.2',
  locale: 'en-US',
});

const audioUrl = response.url;
console.log(`Audio available at: ${audioUrl}`);

Fetch the audio later with the same x-api-key header.

Returns: Promise<{ url: string }> — an object with a url key pointing to the generated audio.

Parameters

ParameterTypeDefaultDescription
textstringRequiredText to convert to speech.
params.voicePromptIdstring—Voice prompt ID to use. Either this or voiceReference must be provided.
params.voiceReferencestring | Buffer—Audio reference for instant voice cloning. Accepts a file path, raw Buffer, or base64-encoded string. Either this or voicePromptId must be provided.
params.modelstringdd-etts-3.2Model ID.
params.localestringen-USLanguage locale code.
paramsTtsParams—Supports all tts() parameter fields. Retroactive generation is most commonly used with voicePromptId, model, and locale.

WebSocket TTS

generateToBuffer() — Generate to buffer

Generate audio and receive a Buffer of audio data. WebSocket generation returns WAV by default.

const deepdub = new DeepdubClient('dd-your-api-key');
await deepdub.connect();

const buffer = await deepdub.generateToBuffer('Hello, welcome to Deepdub!', {
  locale: 'en-US',
  voicePromptId: 'your-voice-id',
});

console.log(`Generated ${buffer.length} bytes of audio`);
deepdub.disconnect();

WebSocket generation defaults to format: 'wav'. Use { protocol: 'http' } on the client for HTTP-based generateToBuffer() with voiceReference or sampleRate for non-mp3 formats.

Returns: Promise<Buffer> — generated audio data.

Parameters

ParameterTypeDefaultDescription
textstringRequiredText to convert to speech.
paramsTtsParams{ format: 'wav' } over WebSocketSupports voicePromptId, voiceReference (HTTP only), model, locale, format, temperature, variance, duration, tempo, seed, promptBoost, sampleRate, accent options, targetGender, generationId, superStretch, realtime, cleanAudio, autoGain, publish, and performanceReferencePromptId.
params.onChunk(chunk: Buffer) => void—Callback receiving each audio chunk as a Buffer. WebSocket protocol only.
params.headerlessbooleanfalseWhen true, chunks passed to onChunk have WAV headers stripped. WebSocket protocol only.

generateToFile() — Generate to file

Generate audio and save directly to a file.

const deepdub = new DeepdubClient('dd-your-api-key');
await deepdub.connect();

await deepdub.generateToFile('./output.wav', 'Hello, welcome to Deepdub!', {
  locale: 'en-US',
  voicePromptId: 'your-voice-id',
});

deepdub.disconnect();

Returns: Promise<Buffer | void> — generated audio data for HTTP protocol, or resolves when the WebSocket file write completes.

Parameters

ParameterTypeDefaultDescription
filePathstringRequiredOutput file path.
textstringRequiredText to convert to speech.
paramsTtsParams{ format: 'wav' } over WebSocketSame generation parameters as generateToBuffer(), including onChunk and headerless.

generateTo() — Low-level generation helper

Generate audio to a selected output type. Most applications should use generateToBuffer() or generateToFile() instead.

await deepdub.connect();

const buffer = await deepdub.generateTo('buffer', 'Hello from the low-level API.', {
  locale: 'en-US',
  voicePromptId: 'your-voice-id',
});

deepdub.disconnect();

Returns: Promise<Buffer | void> — generated audio for buffer output, or resolves when file output completes.

Parameters

ParameterTypeDefaultDescription
outputType'buffer' | 'file'RequiredOutput destination type.
textstringRequiredText to convert to speech.
paramsTtsParams{}Same generation parameters as generateToBuffer(), including onChunk and headerless.
filePathstring | nullnullOutput file path when outputType is 'file'.

Streaming chunks

Receive audio data incrementally for real-time playback:

const deepdub = new DeepdubClient('dd-your-api-key');
await deepdub.connect();

const buffer = await deepdub.generateToBuffer('Streaming audio in real time!', {
  locale: 'en-US',
  voicePromptId: 'your-voice-id',
  model: 'dd-etts-3.2',
  onChunk: (chunk) => {
    console.log(`Received ${chunk.length} bytes`);
    // Stream to an audio player, network response, etc.
  },
});

deepdub.disconnect();

Headerless chunks

Strip WAV headers from each chunk for raw PCM data:

const fs = require('fs');
const deepdub = new DeepdubClient('dd-your-api-key');
await deepdub.connect();

const audioPlayer = fs.createWriteStream('raw-audio.pcm');

await deepdub.generateToBuffer('Raw PCM streaming.', {
  locale: 'en-US',
  voicePromptId: 'your-voice-id',
  headerless: true,
  onChunk: (chunk) => {
    audioPlayer.write(chunk);
  },
});

audioPlayer.end();
deepdub.disconnect();

asyncTts() — Streaming generation

Stream audio chunks over WebSocket for low-latency playback. If no WebSocket is connected, asyncTts() opens one automatically; call disconnect() when finished.

const fs = require('fs');
const deepdub = new DeepdubClient('dd-your-api-key');

fs.mkdirSync('streamed-chunks', { recursive: true });

let chunkIndex = 0;
for await (const chunk of deepdub.asyncTts('Streaming audio in real time!', {
  voicePromptId: 'your-voice-id',
  model: 'dd-etts-3.2',
  locale: 'en-US',
  format: 'wav',
})) {
  const filename = `streamed-chunks/chunk-${String(chunkIndex).padStart(3, '0')}.wav`;
  fs.writeFileSync(filename, chunk);
  console.log(`Received chunk: ${chunk.length} bytes`);
  chunkIndex += 1;
}

deepdub.disconnect();

When streaming WAV output, save each chunk as its own WAV file. Do not concatenate WAV chunks with Buffer.concat(), because each chunk has its own WAV header.

Yields: Buffer — audio chunks as they are generated.

Parameters

ParameterTypeDefaultDescription
textstringRequiredText to convert to speech.
paramsTtsParams{ format: 'wav' } over WebSocketSupports voicePromptId, model, locale, format, temperature, variance, duration, tempo, seed, promptBoost, accent options, sampleRate with mp3, targetGender, and generationId.
params.generationIdstringAuto-generated UUIDOptional UUID for request tracking.
params.targetGenderstring—Target gender for the output voice.
params.onChunk(chunk: Buffer) => void—Internal chunk callback used by the iterator. You usually do not need to pass this directly.
params.headerlessbooleanfalseWhen true, chunks have WAV headers stripped.

Streaming Input

For real-time text streaming, use asyncStreamConnect() to open the streaming-input WebSocket, send text incrementally with asyncStreamText(), signal completion with asyncStreamEnd(), then drain audio with asyncStreamRecvAudio() until it returns null.

const fs = require('fs');
const deepdub = new DeepdubClient('dd-your-api-key');

await deepdub.asyncStreamConnect({
  model: 'dd-etts-3.2',
  locale: 'en-US',
  voicePromptId: 'your-voice-id',
  format: 'wav',
  sampleRate: 16000,
});

fs.mkdirSync('streamed-input-chunks', { recursive: true });

await deepdub.asyncStreamText('Hello, ');
await deepdub.asyncStreamText('this is streamed ');
await deepdub.asyncStreamText('text input.');
await deepdub.asyncStreamEnd();

let chunkIndex = 0;
while (true) {
  const audio = await deepdub.asyncStreamRecvAudio({ timeoutMs: 3000 });
  if (audio === null) {
    break;
  }

  const filename = `streamed-input-chunks/chunk-${String(chunkIndex).padStart(3, '0')}.wav`;
  fs.writeFileSync(filename, audio);
  chunkIndex += 1;
}

deepdub.disconnectStreaming();

For format: 'wav', each audio chunk is a standalone WAV file. Save chunks individually instead of concatenating them into one file.

Streaming input methods

MethodDescription
asyncStreamConnect(params)Connects to baseWebsocketStreamingUrl, reads the initial status, and sends stream-config.
asyncStreamText(text)Sends a text fragment. Call it as many times as needed.
asyncStreamEnd()Signals that no more text will be sent.
asyncStreamRecvAudio()Receives the next audio chunk as a Buffer, or null when complete.
asyncStreamCancel()Cancels the active stream.
asyncStreamPing()Sends a ping and returns the server response.
disconnectStreaming()Closes the streaming-input WebSocket.

Streaming input supports wav, s16le, and mulaw output formats.

Concurrent generations

Run multiple generations in parallel on the same WebSocket connection:

const deepdub = new DeepdubClient('dd-your-api-key');
await deepdub.connect();

const sentences = [
  'First sentence to generate.',
  'Second sentence in parallel.',
  'Third sentence simultaneously.',
];

await Promise.all(
  sentences.map((text, index) =>
    deepdub.generateToFile(`./output_${index}.wav`, text, {
      locale: 'en-US',
      voicePromptId: 'your-voice-id',
      model: 'dd-etts-3.2',
    })
  )
);

deepdub.disconnect();

Voice Management

listVoices() — List all voice prompts

const voices = await deepdub.listVoices();

for (const voice of voices.voicePrompts ?? []) {
  console.log(`${voice.id}: ${voice.name ?? voice.title ?? 'Untitled'}`);
}

Returns: Promise<{ voicePrompts: VoicePrompt[] }> — an object with a voicePrompts key containing voice prompt objects.

Parameters

ParameterTypeDefaultDescription
limitnumber—Optional maximum number of voices to return.

addVoice() — Upload a voice sample

const response = await deepdub.addVoice({
  data: './voice_sample.wav',
  name: 'Professional Narrator',
  gender: 'female',
  locale: 'en-US',
  publish: false,
  speakingStyle: 'Neutral',
  age: 30,
});

console.log(`Created voice: ${JSON.stringify(response)}`);

Returns: Promise<object> — created voice prompt information.

Parameters

ParameterTypeDefaultDescription
datastring | BufferRequiredAudio data: file path, raw Buffer, or base64-encoded string.
namestringRequiredDisplay name for the voice prompt.
genderstringRequiredSpeaker gender: "male" or "female". Sent to the API as uppercase.
localestringRequiredLanguage locale code (e.g. en-US).
publishbooleanfalseWhether to make the voice publicly available.
speakingStylestring'Neutral'Speaking style descriptor.
agenumber0Age of the speaker.
filenamestringDerived from dataFile name to send with the voice sample.
textstring—Transcript or text associated with the voice sample.
speakerIdstring—Speaker ID to associate with the voice prompt.

CLI Reference

# List available voices
deepdub list-voices

# Upload a new voice
deepdub add-voice \
  --file path/to/audio.mp3 \
  --name "My Voice" \
  --gender male \
  --locale en-US

# Generate text-to-speech
deepdub tts \
  --text "Hello from the CLI!" \
  --voice-prompt-id your-voice-id \
  --out output.mp3

# Set API key via flag or environment
deepdub --api-key dd-your-key tts --text "Hello!" --voice-prompt-id your-id
export DEEPDUB_API_KEY=dd-your-key

Environment Variables

VariableDescriptionDefault
DEEPDUB_API_KEYAPI key for authentication—
DEEPDUB_BASE_URLREST API base URLUS/EU production URL
DEEPDUB_BASE_WEBSOCKET_URLWebSocket API base URLUS/EU production URL
DEEPDUB_BASE_WEBSOCKET_STREAMING_URLStreaming WebSocket URLwss://wss.deepdub.ai/ws
DD_EUUse EU endpoints ("1" to enable)"0"

Error Handling

try {
  const audio = await deepdub.tts('Hello!', {
    voicePromptId: 'your-voice-id',
  });
} catch (error) {
  if (error.status === 401) {
    console.error('Invalid API key');
  } else if (error.status === 400) {
    console.error('Invalid request parameters:', error.message);
  } else {
    console.error('API error:', error.message);
  }
}

For WebSocket operations, server errors are thrown as Error with the server message, such as rate limits or insufficient credits.

Available Models

Model IDDescription
dd-etts-3.2Latest model (default)
dd-etts-3.0High-quality production model
dd-etts-2.5Stable production model

Tests

Live API tests require DEEPDUB_API_KEY in .env:

npm test
npm run test:readme

Set DEEPDUB_VOICE_REFERENCE_FILE to a real reference audio file to enable the optional voice reference test. Set DEEPDUB_RUN_ADD_VOICE=1 to include README examples that create persisted voice prompts.

Individual suites: node test/test-tts.js, node test/test-async-tts.js, node test/test-eu-region.js, etc.

版本与发布记录

@deepdub/node 共发布 12 个版本,首次发布于 2024/12/10;过去 12 个月发布了 8 个版本。

版本发布日期距今
3.0.2latest2026/06/294 个月前
3.0.12026/06/294 个月前
3.0.02026/06/294 个月前
2.0.02026/05/205 个月前
1.2.32026/01/259 个月前
1.2.22026/01/259 个月前

其他发布通道:beta → 1.0.0-beta.0。

关于 @deepdub/node 的常见问题

@deepdub/node 是什么?

Deepdub API SDK

如何安装 @deepdub/node?

在项目目录运行 npm install @deepdub/node,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 deepdub,可以用 npx deepdub 直接运行。

@deepdub/node 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@deepdub/node 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@deepdub/node 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@deepdub/node 可以商用吗?

@deepdub/node 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@deepdub/node 的下载量有多少?

根据 npm 官方下载统计,@deepdub/node 在 2026/10/12 – 2026/11/10 这 30 天内被下载 4,848 次,日均约 162 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@deepdub/node 还在维护吗?

最新版本 3.0.2 发布于 2026/06/29(4 个月前);至今共发布 12 个版本,其中过去 12 个月发布了 8 个;首次发布于 2024/12/10。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。