seed-tts-2.0 Text-to-Speech

Convert text into speech for content narration, voiceovers, and voice interactions. This document uses MaiToken's native HTTP unidirectional streaming interface: submit text once and continuously receive audio data.

POST/api/v3/tts/unidirectional

Integration Preparation

  1. Create an API Key in the MaiToken Console.
  2. Ensure that the group selected for the API Key is authorized to use seed-tts-2.0 and has sufficient available balance.
  3. Prepare the text and a voice ID supported by this model.

The example uses a placeholder API Key. Replace it with your production environment Key. A backend login Token cannot be used as a model invocation Key.

Endpoint

POST https://{BASE_URL}/api/v3/tts/unidirectional

This uses the complete native API path. Do not prepend /v1 to the URL.

Request Headers

Field Required Description
X-Api-Key Yes MaiToken API Key. Enter the Key directly without adding Bearer
X-Api-Resource-Id Yes Fixed as seed-tts-2.0
Content-Type Yes application/json; charset=utf-8

Request Body

{  "req_params": {    "text": "Hello, welcome to MaiToken text-to-speech.",    "speaker": "zh_female_vv_uranus_bigtts",    "audio_params": {      "format": "mp3",      "sample_rate": 24000    }  }}
Parameter Type Description
req_params.text string Text to synthesize. It must contain readable content and use UTF-8 encoding
req_params.speaker string Voice ID. It must match the model version; the example voice is zh_female_vv_uranus_bigtts
req_params.audio_params.format string The example explicitly specifies mp3
req_params.audio_params.sample_rate integer The example explicitly specifies a sample rate of 24000 Hz

This interface selects the model through request headers, so no additional model field is required at the top level of the request body. Voice availability depends on the authorization of the currently connected resource.

Bash / cURL Example

The following example applies to Bash and Git Bash. The test text uses JSON Unicode escapes to represent “Hello”, avoiding the effects of terminal character encoding on the test result.

export MAITOKEN_API_KEY='Replace with your production environment API Key' curl --fail-with-body --silent --show-error --no-buffer \  'https://{BASE_URL}/api/v3/tts/unidirectional' \  -H "X-Api-Key: ${MAITOKEN_API_KEY}" \  -H 'X-Api-Resource-Id: seed-tts-2.0' \  -H 'Content-Type: application/json; charset=utf-8' \  --data-binary '{"req_params":{"text":"\u4f60\u597d","speaker":"zh_female_vv_uranus_bigtts","audio_params":{"format":"mp3","sample_rate":24000}}}' \  --output tts-response.jsonstream

Do not add spaces after the trailing backslash \ on each line. The response file is a JSON data stream and cannot be renamed directly to MP3 and played.

Response and Audio Reconstruction

The HTTP response body consists of multiple JSON objects. The data field of each audio object contains Base64 data, which must be decoded in sequence and concatenated. JSON objects may be separated by line breaks or may appear consecutively; do not assume that one network data chunk is one complete JSON object.

The following illustrates the structure. <Base64 audio segment> is not playable data:

{"code":0,"message":"","data":"<Base64 audio segment>"}{"code":0,"message":"","data":"<Base64 audio segment>"}{"code":20000000,"message":"ok","data":null,"usage":{"text_words":2}}

code=0 indicates a normal successful data frame; code=20000000 indicates that synthesis has completed successfully. usage.text_words is the usage reported by the upstream service and may appear only in the final frame. Even when the HTTP status is 200, you should check the business error code in the response. See the upstream HTTP unidirectional streaming documentation for the response protocol.

Complete Python Example: Request and Save an MP3

This example uses only the Python standard library and does not require installing an SDK. After receiving the complete response, it parses the concatenated JSON frames, checks the business status, and then writes the audio file. It is suitable for integration testing, but is not an example of real-time playback.

Save the code as seed_tts.py:

import base64import jsonimport osfrom pathlib import Pathfrom urllib.error import HTTPErrorfrom urllib.request import Request, urlopen  def decode_audio(raw):    decoder = json.JSONDecoder()    offset = 0    audio = bytearray()    usage = None    finished = False     while offset < len(raw):        if raw[offset].isspace():            offset += 1            continue        frame, offset = decoder.raw_decode(raw, offset)        if not isinstance(frame, dict):            raise RuntimeError("Response frame is not a JSON object")        code = frame.get("code")        if code not in (0, 20000000):            raise RuntimeError(f"Synthesis failed: {code}, {frame.get('message', frame)}")        if frame.get("data"):            audio.extend(base64.b64decode(frame["data"], validate=True))        if isinstance(frame.get("usage"), dict):            usage = frame["usage"]        if code == 20000000:            finished = True     if not finished:        raise RuntimeError("No successful synthesis end frame received; check whether the connection was interrupted")    if not audio:        raise RuntimeError("Response contains no audio data")    return bytes(audio), usage  def main():    payload = {        "req_params": {            "text": "Hello, welcome to MaiToken text-to-speech.",            "speaker": "zh_female_vv_uranus_bigtts",            "audio_params": {"format": "mp3", "sample_rate": 24000},        }    }    request = Request(        "https://{BASE_URL}/api/v3/tts/unidirectional",        data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),        headers={            "X-Api-Key": os.environ["MAITOKEN_API_KEY"],            "X-Api-Resource-Id": "seed-tts-2.0",            "Content-Type": "application/json; charset=utf-8",        },        method="POST",    )    try:        with urlopen(request, timeout=120) as response:            raw = response.read().decode("utf-8")    except HTTPError as exc:        detail = exc.read().decode("utf-8", errors="replace")        raise RuntimeError(f"HTTP {exc.code}: {detail}") from exc     audio, usage = decode_audio(raw)    Path("speech.mp3").write_bytes(audio)    print(f"Saved speech.mp3 ({len(audio)} bytes); usage: {usage}")  if __name__ == "__main__":    main()

Run:

export MAITOKEN_API_KEY='replace-with-your-production-api-key'python seed_tts.py

If you saved the response using the cURL command above, you can reuse the parsing function to reconstruct the audio without calling the API again:

python -c 'from pathlib import Path; from seed_tts import decode_audio; audio, usage = decode_audio(Path("tts-response.jsonstream").read_text(encoding="utf-8")); Path("speech.mp3").write_bytes(audio); print(usage)'

Usage and Billing

This model is billed by character usage, with prices uniformly quoted per 10,000 characters. The actual sales price is determined by MaiToken's current model pricing and account group.

Amount charged = Billable characters ÷ 10,000 × Sales price per 10,000 characters × Group multiplier × User multiplier

For example, if the price is 0.08 credits per 10,000 characters, the billable character count is 1,000, and both the group and user multipliers are 1, the charge is 0.008 credits. This price is provided only to demonstrate the formula and is not a production quote.

An estimated charge may be held when the request begins. The final charge is settled according to actual usage, and any difference is reconciled. Check the preauthorized amount and final charge separately. Actual usage is determined by the settlement record in the request logs; do not calculate the character count simply from the number of UTF-8 bytes.

Troubleshooting

Symptom Troubleshooting Steps
curl: (3) URL rejected Check the URL quotation marks, invisible characters, and line-continuation backslashes. If necessary, combine the command into a single line.
unsupported_endpoint Confirm that the full path is /api/v3/tts/unidirectional, with /api/v3 included and no extra /v1.
No readable text! Confirm that the text is in req_params.text, is non-empty, and contains content that can be spoken. Use the Unicode-escaped text from the example to rule out encoding issues.
HTTP 401 Check that you are using a valid MaiToken API Key rather than an admin console login token.
Insufficient balance Check the available balance and any funds held by in-progress requests.
Voice permission error Check that speaker is supported by the current model and that your account is authorized to use the voice.
HTTP 429 / concurrency limit Reduce concurrency and use backoff retries based on the information returned by the API.
File cannot be played Confirm that each data fragment was Base64-decoded and concatenated in order, and that the JSON response was not saved directly as an MP3 file.
Connection interrupted / missing end frame Do not treat partial audio as a complete success. Check the request status and billing record before deciding whether to retry the request.

Documentation Sources

  • MaiToken API Documentation Overview: Production API domain and integration entry point.
  • MaiToken Speech Synthesis: The main content of this page is currently empty; this document provides supplementary usage instructions.
  • Upstream HTTP Unidirectional Streaming Protocol: Audio frame and end-frame semantics.
  • The platform endpoint path, request passthrough behavior, character usage, and billing units were verified against the current gateway and metering implementations. No paid synthesis request was made using a real API Key for this document.

Verified on: 2026-09-24.