ストリーミング

チャンク転送エンコーディングを使用して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();