Skip to navigation

HTTP Streaming API

View as Markdown

POST /text-to-speech/stream returns audio as a raw binary stream that starts arriving while the text is still being synthesized. You can save it, pipe it to a player or forward it to a client without waiting for the full file. It needs no WebSocket handshake, config message or connection management.

EndpointPOST https://api.sarvam.ai/text-to-speech/stream
Auth headerapi-subscription-key: <your key>
Max text3,500 characters per request
Default outputMP3, 128k bitrate, 22,050 Hz
ResponseRaw audio bytes, not JSON and not base64

Typical uses are server-side audio generation, proxying audio to a web or mobile client, batch jobs, and serverless or edge runtimes where WebSockets are not available.

HTTP Stream or WebSocket

HTTP StreamWebSocket
ProtocolOne POST per requestPersistent connection
SetupNoneHandshake, then a config message
Texts per connectionOneMany
Max text3,500 characters2,500 characters per message
Audio outputRaw binary streamJSON messages with base64 audio
Best forOne-shot generation and pipelinesVoice agents streaming text from an LLM

Choose HTTP Stream when you already have the full text. Choose WebSocket when text arrives incrementally or you send many utterances on one connection. For a three-way comparison including REST, see Which API to use.

Quickstart

Set your API key as the SARVAM_API_KEY environment variable, then run one of these. Each writes the streamed audio to output.mp3.

import os
from sarvamai import SarvamAI
client = SarvamAI(api_subscription_key=os.environ["SARVAM_API_KEY"])
with open("output.mp3", "wb") as f:
for chunk in client.text_to_speech.convert_stream(
text="नमस्ते! Sarvam AI में आपका स्वागत है।",
language_code="hi-IN",
model="bulbul:v4-flash",
speaker="simran_en_customer",
output_audio_codec="mp3",
):
f.write(chunk)

Always pass speaker explicitly. The Python SDK’s default speaker is not valid for current models, and the API default depends on model.

To play audio as it arrives, pipe the response into a player. This needs ffmpeg installed.

curl -sN -X POST https://api.sarvam.ai/text-to-speech/stream \
-H "api-subscription-key: $SARVAM_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"text": "This is a live playback test.",
"language_code": "en-IN",
"model": "bulbul:v4-flash",
"speaker": "simran_en_customer"
}' | ffplay -nodisp -autoexit -

Request parameters

ParameterTypeRequiredDefaultDescription
textstringYesnoneText to convert. 1 to 3,500 characters. Code-mixed text is supported.
language_codestringNoen-INBCP-47 code: hi-IN, bn-IN, ta-IN, te-IN, gu-IN, kn-IN, ml-IN, mr-IN, pa-IN, od-IN, en-IN
modelstringNobulbul:v3bulbul:v4-flash or bulbul:v3
speakerstringNoDepends on modelshubh_enhi_ads for bulbul:v4-flash, shubh for bulbul:v3. See Voices.
output_audio_codecstringNomp3mp3, wav, aac, flac, linear16, mulaw, alaw, opus
output_audio_bitratestringNo128k32k, 64k, 96k, 128k, 192k
speech_sample_rateintegerNo22050Output sample rate in Hz: 8000, 16000, 22050, 24000
pacenumberNo1.0Speech speed, 0.5–2.0
pitchnumberNo0.0Pitch shift, -0.5–0.5
loudnessnumberNo1.0Volume multiplier, 0.1–2.5
temperaturenumberNo0.6Expressiveness, 0.01–1.0
enable_preprocessingbooleanNofalseNormalize English words and numbers before synthesis
dict_idstringNononeID of a pronunciation dictionary (format p_xxxxxxxx)
enable_cached_responsesbooleanNofalseEnable response caching (beta)

Streaming supports sample rates up to 24,000 Hz only. 32000, 44100 and 48000 are available on the REST API and return a 400 here. opus fails with a 400 at the default 22,050 Hz, so set speech_sample_rate to 8000, 16000 or 24000 when you use it. Unknown request fields are ignored without an error.

Response

The body is raw audio in the codec you requested, sent with chunked transfer. It is not JSON and not base64, so write the bytes straight to a file or a player. Unlike the REST API, nothing needs decoding.

output_audio_codecContent-Type
mp3audio/mpeg
wavaudio/wav
aacaudio/aac
flacaudio/flac
linear16audio/pcm
mulawaudio/mulaw
alawaudio/alaw
opusaudio/opus (Ogg container)

Use a pronunciation dictionary

Pass dict_id to apply your custom pronunciations while streaming. Replace p_5cb7faa6 with the ID of a dictionary you created. An unknown dict_id returns a 500 (“error preprocessing input text”) on this endpoint, where the REST API returns a 404, so confirm the ID exists first.

import os
from sarvamai import SarvamAI
client = SarvamAI(api_subscription_key=os.environ["SARVAM_API_KEY"])
with open("output.mp3", "wb") as f:
for chunk in client.text_to_speech.convert_stream(
text="NEFT ट्रांसफर करें और KYC पूरा करें।",
language_code="hi-IN",
model="bulbul:v4-flash",
speaker="simran_en_customer",
dict_id="p_5cb7faa6",
):
f.write(chunk)

See the Pronunciation Dictionary guide to create a dictionary.

Errors

Validation errors are returned as JSON, not audio. Check the status code before you treat the body as audio.

{
"error": {
"message": "Speaker 'nope' is not recognized. Available speakers for bulbul:v3 are: aditya, ritu, ...",
"code": "invalid_request_error",
"request_id": "20261119_b6eb57d5-a8fd-40af-9009-08e0a9eb4916"
}
}
StatusCauseFix
400text is longer than 3,500 charactersSplit the text and send several requests
400speaker does not belong to modelThe error message lists the valid speakers for that model
400Invalid language_codeThe error message lists the valid codes
400Unsupported speech_sample_rate, or opus at 22,050 HzUse a rate from the parameter table
403Invalid or missing API keyCheck the api-subscription-key header
429Rate limit exceededWait and retry with backoff. See Credits & Rate Limits.

The full code table and SDK exception reference are on Errors & Troubleshooting.

import os
from sarvamai import SarvamAI
from sarvamai.core.api_error import ApiError
client = SarvamAI(api_subscription_key=os.environ["SARVAM_API_KEY"])
try:
with open("output.mp3", "wb") as f:
for chunk in client.text_to_speech.convert_stream(
text="Hello from Sarvam AI!",
language_code="en-IN",
model="bulbul:v4-flash",
speaker="simran_en_customer",
):
f.write(chunk)
except ApiError as e:
print(f"Error {e.status_code}: {e.body}")

See the API Reference for the full endpoint spec.

Need help? Reach out on Discord.