流式传输

了解如何使用分块传输编码从 ElevenLabs API 流式获取实时音频

ElevenLabs API 支持部分端点的实时音频流式传输,通过 HTTP 使用分块传输编码直接返回原始音频字节(例如 MP3 数据)。客户端可在音频生成时逐步处理或播放。

官方 Node 和 Python 库提供了简化持续音频流处理的实用工具。

文本转语音 API、变声器 API 和 音频分离 API 均支持流式传输。本节重点介绍向文本转语音 API 发出的请求如何进行流式传输。

在 Python 中,流式请求如下:

from elevenlabs import stream
from elevenlabs.client import ElevenLabs
elevenlabs = ElevenLabs()
audio_stream = elevenlabs.text_to_speech.stream(
text="This is a test",
voice_id="JBFqnCBsd6RMkjVDRZzb",
model_id="eleven_multilingual_v2"
)
# option 1: play the streamed audio locally
stream(audio_stream)
# option 2: process the audio bytes manually
for chunk in audio_stream:
if isinstance(chunk, bytes):
print(chunk)

在 Node / Typescript 中,流式请求如下:

import { ElevenLabsClient, stream } from "@elevenlabs/elevenlabs-js";
import { Readable } from "stream";
const elevenlabs = new ElevenLabsClient();
async function main() {
const audioStream = await elevenlabs.textToSpeech.stream("JBFqnCBsd6RMkjVDRZzb", {
text: "This is a test",
modelId: "eleven_v4",
});
// option 1: play the streamed audio locally
await stream(Readable.from(audioStream));
// option 2: process the audio manually
for await (const chunk of audioStream) {
console.log(chunk);
}
}
main();