Depdub 节点.js SDK
安装并使用 Depdub Node.js SDK 用于文本到语音生成,并有流支持.
安装
npm install --save @deepdub/node
# or
yarn add @deepdub/node
所需经费: 节点.js 18+(使用本地 fetch(中文(简体) )
初始化
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' });
构造参数
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
apiKey | string | process.env.DEEPDUB_API_KEY | 您的 Deepdub API 密钥 。 倒计时 DEEPDUB_API_KEY 如果没有提供的话. |
options.protocol | 'websocket' | 'http' | 'websocket' | 运输协议 : "websocket" 用于实时流线,或 "http" 为REST API. |
options.baseUrl | string | US/EU REST URL 美国/EU REST URL | REST API 的基础 URL 。 倒计时 DEEPDUB_BASE_URL。 。 。 . |
options.baseWebsocketUrl | string | 美国/欧盟 WebSocket URL | WebSocket API 的基础 URL. 倒计时 DEEPDUB_BASE_WEBSOCKET_URL。 。 。 . |
options.baseWebsocketStreamingUrl | string | wss://wss.deepdub.ai/ws | WebSocket流式API的基础URL. 倒计时 DEEPDUB_BASE_WEBSOCKET_STREAMING_URL。 。 。 . |
options.eu | boolean | false | 使用欧盟区域终点. 倒计时 DD_EU=1。 。 。 . |
协议比较
| 特性 | 网络安全套 | HTTP 密码 |
|---|---|---|
流出块( E)onChunk(中文(简体) ) | 对 | 没有 |
sampleRate 选项 | mp3 仅限 | 所有格式 |
voiceReference 选项 | 没有 | 对 |
| 同时代人 | 对 | 对 |
使用 网络安全套 (默认)用于实时流回和低纬度回放. 使用 HTTP 密码 需要的时候 voiceReference 即时语音克隆或 sampleRate 带有非mp3格式.
区域终点
| 地区 | (原始内容存档于2013-10-12) (英语). REST API | WebSocket API 服务器 |
|---|---|---|
| US( 默认) | https://restapi.deepdub.ai/api/v1 | wss://wsapi.deepdub.ai/open |
| 欧盟 | https://restapi.eu.deepdub.ai/api/v1 | wss://wsapi.eu.deepdub.ai/open |
启用欧盟 { eu: true } 或者说 DD_EU=1。 。 。 .
连接
对于 WebSocket 协议,请拨 connect() 在使用前 generateToBuffer(), (中文(简体) ), generateToFile(),或 generateTo()。对于增量文本流,调用 asyncStreamConnect()。对于 HTTP 协议和 REST 方法,不需要连接步骤.
connect() — 打开 WebSocket 连接
const deepdub = new DeepdubClient('dd-your-api-key');
await deepdub.connect();
回返情况: Promise<WebSocket> ——已打开的WebSocket连接.
参数
无参数 .
asyncConnect() -别提了 connect()
await deepdub.asyncConnect();
回返情况: Promise<WebSocket> ——已打开的WebSocket连接.
参数
无参数 .
disconnect() — 关闭 WebSocket 连接
await deepdub.connect();
// ...generate audio...
deepdub.disconnect();
打电话 disconnect() 当你完成 WebSocket。 如果你跳过它,打开的连接可以使节点.js进程保持活性.
回返情况: void
参数
无参数 .
文字对语言
tts() - 同步生成
生成语音并接收完整的音频 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);
回返情况: Promise<Buffer> ——指定格式的二进制音频数据.
参数
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
text | string | 需求 | 要转换为语音的文本 . |
params.voicePromptId | string | —— 说 | 语音提示ID使用. 要么这样 voiceReference 必须提供. |
params.voiceReference | string | Buffer | —— 说 | 即时语音克隆的音频参考. 接受文件路径, 原始 Buffer,或基数64-编码字符串。 要么这样 voicePromptId 必须提供. |
params.model | string | dd-etts-3.2 | 型号ID. |
params.locale | string | en-US | 语言地语区号(如:. en-US, (中文(简体) ), fr-FR) (中文(简体) ). |
params.format | string | mp3 | 音频输出格式 。 REST 支持 mp3, (中文(简体) ), opus,以及 mulaw。 。 。 . |
params.temperature | number | —— 说 | 生成温度(0.0-1.0). 较高的值产生更多样化的产出. |
params.variance | number | —— 说 | 语音变位(0.0-1.0). |
params.duration | number | —— 说 | 目标音频持续时间数秒。 相互独占 tempo。 。 。 . |
params.tempo | number | —— 说 | 回放速度乘数. 相互排斥 duration。 。 。 . |
params.seed | number | —— 说 | 随机种子供决定代相. |
params.promptBoost | boolean | —— 说 | 增强语音提示特性. |
params.sampleRate | number | —— 说 | 输出样本率以 Hz 为单位。 支持 : 8000, (中文(简体) ), 16000, (中文(简体) ), 22050, (中文(简体) ), 24000, (中文(简体) ), 44100, (中文(简体) ), 48000。 。 。 . |
params.accentBaseLocale | string | —— 说 | (原始内容存档于2017-10-12). Base sign locale. 必须与 accentLocale 财务报告和审定财务报表 accentRatio。 。 。 . |
params.accentLocale | string | —— 说 | 目标口音地方。 必须与 accentBaseLocale 财务报告和审定财务报表 accentRatio。 。 。 . |
params.accentRatio | number | —— 说 | 百分率混合比率(0.0-1.0). 必须与 accentBaseLocale 财务报告和审定财务报表 accentLocale。 。 。 . |
params.accentControl | object | —— 说 | 中央混合对象 : { accentBaseLocale, accentLocale, accentRatio }。 。 。 . |
params.targetGender | string | —— 说 | 产出声音的性别指标. |
params.generationId | string | 自动生成的 UUID | 请求跟踪可选 UUID . |
params.superStretch | boolean | —— 说 | 为更长的音频启用超级拉伸 . |
params.realtime | boolean | —— 说 | 启用实时优先级处理 . |
params.cleanAudio | boolean | —— 说 | API支持时请求音频清理. |
params.autoGain | boolean | —— 说 | API支持时请求自动增益控制. |
params.publish | boolean | —— 说 | API 支持时公布生成的资产 . |
params.performanceReferencePromptId | string | —— 说 | 语音提示ID作为性能参考. |
所有通用 TTS 参数的完整示例
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);
从音频引用语音克隆
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() ——逆向生成
提交 TTS 请求并接收一个 URL 供以后检索 .
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}`);
稍后用相同的方式获取音频 x-api-key 头曰.
回返情况: Promise<{ url: string }> - 具有下列特性的物体: url 键指向生成的音频.
参数
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
text | string | 需求 | 要转换为语音的文本 . |
params.voicePromptId | string | —— 说 | 语音提示ID使用. 要么这样 voiceReference 必须提供. |
params.voiceReference | string | Buffer | —— 说 | 即时语音克隆的音频参考. 接受文件路径, 原始 Buffer,或基数64-编码字符串。 要么这样 voicePromptId 必须提供. |
params.model | string | dd-etts-3.2 | 型号ID. |
params.locale | string | en-US | 语言地语区号. |
params | TtsParams | —— 说 | 全部支持 tts() 参数字段。 反向生成最常用的是 voicePromptId, (中文(简体) ), model,以及 locale。 。 。 . |
网络口袋 TTS
generateToBuffer() — 生成为缓冲
生成音频并接收 Buffer 音频数据。 WebSocket生成默认返回WAV.
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 生成默认为 format: 'wav'启用 { protocol: 'http' } 基于 HTTP 的客户端 generateToBuffer() 与 voiceReference 或者说 sampleRate 用于非mp3格式.
回返情况: Promise<Buffer> ——生成音频数据.
参数
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
text | string | 需求 | 要转换为语音的文本 . |
params | TtsParams | { format: 'wav' } 通过 WebSocket | 支助 voicePromptId, (中文(简体) ), voiceReference (仅限HTTP), model, (中文(简体) ), locale, (中文(简体) ), format, (中文(简体) ), temperature, (中文(简体) ), variance, (中文(简体) ), duration, (中文(简体) ), tempo, (中文(简体) ), seed, (中文(简体) ), promptBoost, (中文(简体) ), sampleRate重音选项, targetGender, (中文(简体) ), generationId, (中文(简体) ), superStretch, (中文(简体) ), realtime, (中文(简体) ), cleanAudio, (中文(简体) ), autoGain, (中文(简体) ), publish,以及 performanceReferencePromptId。 。 。 . |
params.onChunk | (chunk: Buffer) => void | —— 说 | 调回每个音频块 Buffer只有WebSocket协议. |
params.headerless | boolean | false | 何时 true,块传递给 onChunk wAV头被剥了 只有WebSocket协议. |
generateToFile() — 生成为文件
生成音频并直接保存到文件 .
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();
回返情况: Promise<Buffer | void> ——为HTTP协议生成了音频数据,或者当WebSocket文件写入完成后解决.
参数
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
filePath | string | 需求 | 输出文件路径 . |
text | string | 需求 | 要转换为语音的文本 . |
params | TtsParams | { format: 'wav' } 通过 WebSocket | 生成参数与 generateToBuffer(),包括: onChunk 财务报告和审定财务报表 headerless。 。 。 . |
generateTo() – 低级生成辅助器
生成音频到选中输出类型 。 大多数应用程序应当使用 generateToBuffer() 或者说 generateToFile() 换句话说.
await deepdub.connect();
const buffer = await deepdub.generateTo('buffer', 'Hello from the low-level API.', {
locale: 'en-US',
voicePromptId: 'your-voice-id',
});
deepdub.disconnect();
回返情况: Promise<Buffer | void> ——生成用于缓冲输出的音频,或当文件输出完成后解析.
参数
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
outputType | 'buffer' | 'file' | 需求 | 输出目标类型 . |
text | string | 需求 | 要转换为语音的文本 . |
params | TtsParams | {} | 生成参数与 generateToBuffer(),包括: onChunk 财务报告和审定财务报表 headerless。 。 。 . |
filePath | string | null | null | 当输出文件路径 outputType 实值 'file'。 。 。 . |
流出块
用于实时播放的音频数据递增接收 :
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();
无头块
从每个块取出 WAV 信头用于原始PCM 数据 :
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() ——流体发电
在 WebSocket 上流音频块用于低频回放 。 如果没有WebSocket连接, asyncTts() 自动打开; 调用 disconnect() 当完成.
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();
当流出WAV输出时,将每个块保存为自己的WAV文件. 不要将 WAV 块与 Buffer.concat(),因为每个块都有自己的WAV头.
仪: Buffer ——生成的音频块.
参数
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
text | string | 需求 | 要转换为语音的文本 . |
params | TtsParams | { format: 'wav' } 通过 WebSocket | 支助 voicePromptId, (中文(简体) ), model, (中文(简体) ), locale, (中文(简体) ), format, (中文(简体) ), temperature, (中文(简体) ), variance, (中文(简体) ), duration, (中文(简体) ), tempo, (中文(简体) ), seed, (中文(简体) ), promptBoost重音选项, sampleRate 与 mp3, (中文(简体) ), targetGender,以及 generationId。 。 。 . |
params.generationId | string | 自动生成的 UUID | 请求跟踪可选 UUID . |
params.targetGender | string | —— 说 | 产出声音的性别指标. |
params.onChunk | (chunk: Buffer) => void | —— 说 | 内块调用器使用 。 您通常不需要直接通过 . |
params.headerless | boolean | false | 何时 true块头有WAV头被剥了. |
流出输入
用于实时文本流, 使用 asyncStreamConnect() 打开流入的 WebSocket, 以渐进方式发送文本 asyncStreamText(),以 asyncStreamEnd(),然后用 asyncStreamRecvAudio() 直到它回来 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();
对于 format: 'wav',每个音频块是一个独立的WAV文件. 将块单独保存, 而不是将其缩入一个文件 .
流入法
| 方法 | 说明 |
|---|---|
asyncStreamConnect(params) | 连接到 baseWebsocketStreamingUrl,读取初始状态,并发送 stream-config。 。 。 . |
asyncStreamText(text) | 发送文本碎片。 随所需要而称之. |
asyncStreamEnd() | 不再发送文本的信号 . |
asyncStreamRecvAudio() | 接收下一个音频块为 a Buffer,或 null 当完成. |
asyncStreamCancel() | 取消活动流. |
asyncStreamPing() | 发送一个ping并返回服务器响应. |
disconnectStreaming() | 关闭流入WebSocket. |
流程输入支持 wav, (中文(简体) ), s16le,以及 mulaw 输出格式.
同时代人
在同一 WebSocket 连接上并行运行多代 :
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();
语音管理
listVoices() — 列出所有语音提示
const voices = await deepdub.listVoices();
for (const voice of voices.voicePrompts ?? []) {
console.log(`${voice.id}: ${voice.name ?? voice.title ?? 'Untitled'}`);
}
回返情况: Promise<{ voicePrompts: VoicePrompt[] }> - 具有下列特性的物体: voicePrompts 键中包含语音提示对象.
参数
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
limit | number | —— 说 | 可选的最大声数返回 . |
addVoice() ——上传语音样本
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)}`);
回返情况: Promise<object> ——创建语音提示信息.
参数
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
data | string | Buffer | 需求 | 音频数据: 文件路径, 原始 Buffer,或基数64-编码字符串. |
name | string | 需求 | 为语音提示显示名称 . |
gender | string | 需求 | 发言者性别: "male" 或者说 "female"。发送到API作为大写. |
locale | string | 需求 | 语言地语区号(如:. en-US) (中文(简体) ). |
publish | boolean | false | 是否公开声音. |
speakingStyle | string | 'Neutral' | 说话风格描述符. |
age | number | 0 | 发言者的年龄. |
filename | string | 衍生自 data | 随语音样本发送的文件名 . |
text | string | —— 说 | 与语音样本相接的语录或文字. |
speakerId | string | —— 说 | 扬声器ID与语音提示连接. |
CLI 参考
# 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
环境变量
| 变量 | 说明 | 默认 |
|---|---|---|
DEEPDUB_API_KEY | 认证的 API 密钥 | —— 说 |
DEEPDUB_BASE_URL | REST API 基础 URL | 美国/欧盟生产 URL |
DEEPDUB_BASE_WEBSOCKET_URL | WebSocket API 基础 URL | 美国/欧盟生产 URL |
DEEPDUB_BASE_WEBSOCKET_STREAMING_URL | 正在流出 WebSocket URL | wss://wss.deepdub.ai/ws |
DD_EU | 使用欧盟终点( E)"1" 页:1 | "0" |
处理错误
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);
}
}
对于 WebSocket 操作,服务器错误被抛出为 Error 包含服务器消息,例如利率限制或信用值不足.
可用模式
| 型号标识 | 说明 |
|---|---|
dd-etts-3.2 | 最新模式( 默认) |
dd-etts-3.0 | 高质量生产模式 |
dd-etts-2.5 | 稳定的生产模式 |
测试
需要实时API测试 DEEPDUB_API_KEY 内 .env数字 :
npm test
npm run test:readme
设定 DEEPDUB_VOICE_REFERENCE_FILE 以启用可选语音引用测试.
设定 DEEPDUB_RUN_ADD_VOICE=1 包括创建持续语音提示的README实例.
个人套房: node test/test-tts.js, (中文(简体) ), node test/test-async-tts.js, (中文(简体) ), node test/test-eu-region.js等 (中文(简体) ).