DeepSeek TTS needs a successful finish, not just audio bytes

Compare DeepSeek TTS HTTP and WebSocket modes, validate the finish event, and package 24 kHz PCM as WAV with a complete Python example that preserves an existing output on failure.

DeepSeek TTS needs a successful finish, not just audio bytes

DeepSeek TTS accepts either complete text over HTTP or text chunks over WebSocket. A working integration must establish how input ends, how audio bytes should be decoded, and whether synthesis completed successfully. Saving the first audio frame can turn an interrupted response into a supposedly finished deliverable.

This guide follows the official TTS documentation, checked on December 2, 2026. The short-text WebSocket example was checked with offline simulations; it was not used for authenticated speech generation.

Which mode accepts text as it is generated?

Use HTTP for text already available in full. Use WebSocket to submit text incrementally.

DetailFull-text HTTPStreaming-text WebSocket
Endpointhttps://api.deepseek.com/v1/tools/ttswss://api.deepseek.com/v1/tools/tts
InputJSON text fieldMultiple event: text messages
End of inputEnd of request bodySend event: finish_text
OutputStreaming response bodyBinary audio and text control messages
FormatsWAV by default, or PCMPCM by default, or Opus packets
CompletionHTTP, read errors, and complete-file checksevent: finish with code: success

The HTTP response also streams while synthesis runs. Streaming audio output and incremental text input are separate capabilities. Current voices are stella and tide. Language is detected from text; there is no language parameter. Supported languages include Mandarin, Cantonese, English, and Japanese, among others. Listen to the actual output before delivery.

HTTP accepts complete text; WebSocket accepts chunks followed by finish_text and a final finish

Why can’t PCM or Opus simply be renamed?

PCM contains raw samples. WAV wraps samples with format metadata. The WebSocket Opus option returns packets without a container, so saving those packets with an .ogg suffix does not make an Ogg file.

DeepSeek documents PCM as 24 kHz, 16-bit, mono. Interpreting those bytes as 48 kHz or stereo changes playback. Preserve that metadata or package the data correctly.

For a first file-producing integration, PCM wrapped as WAV is straightforward to inspect. Opus needs a compatible decoding or container pipeline. Streaming audio and playback covers the decoder and buffering boundaries.

PCM plus explicit sample metadata becomes WAV; raw Opus needs a matching pipeline

How do you publish a WAV only after success?

Keep audio in a temporary directory, wait for the success event, validate the complete PCM length, and only then replace the final file. Disconnects, errors, and local timeouts leave an existing speech.wav untouched.

The example requires Python 3.11+ and websockets 14+:

python -m pip install 'websockets>=14'

Set DEEPSEEK_API_KEY in the local or server process. Save this as tts_demo.py and run python tts_demo.py. Its 90-second timeout and 16 MiB file cap are local demonstration limits. It sends one short utterance; continuous duplex playback needs separate send, receive, and buffering arrangements.

import asyncio
import json
import os
from pathlib import Path
import tempfile
import wave

import websockets


async def main():
    output = Path("speech.wav")
    limit = 16 * 1024 * 1024  # This example's local file limit.
    url = "wss://api.deepseek.com/v1/tools/tts?voice_id=stella&format=pcm"
    headers = {"Authorization": f"Bearer {os.environ['DEEPSEEK_API_KEY']}"}

    with tempfile.TemporaryDirectory(dir=output.parent) as folder:
        raw = Path(folder) / "speech.pcm"
        candidate = Path(folder) / "speech.wav"
        received = 0
        finished = False

        async with asyncio.timeout(90):
            async with websockets.connect(
                url, additional_headers=headers, max_size=limit
            ) as ws:
                await ws.send(json.dumps({
                    "event": "text",
                    "text": "Hello, and welcome to this short audio message.",
                }))
                await ws.send(json.dumps({"event": "finish_text"}))
                with raw.open("wb") as audio:
                    async for message in ws:
                        if isinstance(message, bytes):
                            received += len(message)
                            if received > limit:
                                raise RuntimeError("Local audio size limit exceeded")
                            audio.write(message)
                            continue
                        control = json.loads(message)
                        if control.get("event") != "finish":
                            raise RuntimeError("Unexpected control event")
                        if control.get("code") != "success":
                            raise RuntimeError("TTS did not finish successfully")
                        finished = True
                        break

        if not finished or received == 0 or received % 2:
            raise RuntimeError("Missing success event or invalid PCM length")
        with wave.open(str(candidate), "wb") as wav:
            wav.setnchannels(1)
            wav.setsampwidth(2)
            wav.setframerate(24000)
            with raw.open("rb") as audio:
                while chunk := audio.read(65536):
                    wav.writeframesraw(chunk)
        os.replace(candidate, output)
    print(f"Saved {output.name}")


asyncio.run(main())

Each PCM sample occupies two bytes, so the complete stream must have an even length. Individual WebSocket messages can split a sample; validate the combined byte count rather than rejecting every odd-sized frame. Play the resulting WAV and inspect its opening, ending, and spoken content.

Why can synthesis fail after audio arrives?

Audio arrival establishes that synthesis started. WebSocket still requires a successful finish event. For HTTP, the documentation says a failure after output starts cuts off the response.

ObservationApplication behavior
Successful finish and valid audioPackage, then listen to a sample
Connection closes without successMark incomplete; do not publish the final file
Finish carries an errorReport failure and retain the source text and necessary state
Local deadline expiresStop local handling; do not imply resumable synthesis
File decodes but omits a sentenceFail content review despite a valid file header

Speed control and resuming interrupted synthesis are currently unsupported. Resubmission is a new request; handle the earlier result and duplicate delivery explicitly. Reuse an accepted audio file for repeated playback.

Temporary audio becomes a final WAV only after successful completion and length checks

What else should be checked before integration?

Bound text and request size, then test failures and spoken content. Current limits are 10,000 billed characters and 64 KiB of text per request/session. A Chinese character counts as two billed characters. WebSocket sessions end after 60 seconds without new text, last at most 30 minutes, and receive a server ping every 25 seconds.

These are different limits. A ping is not new text and does not replace an application deadline. Check current official pricing before use rather than relying on a temporary promotion.

This example uses DeepSeek’s endpoint and credentials. Nbility’s general audio API uses paths such as /v1/audio/speech; its protocol cannot be inferred from this voice_id or WebSocket URL. Choose the provider and protocol first, then apply pronunciation checks to names, numbers, and ambiguous words before connecting the output to playback.

Related posts

View all posts

Run your Agent workflow through Nbility

Get an API key and connect OpenAI-compatible models and developer tools from one place.

Get an API key