Preparation
- Create an API Key in the MaiToken Console.
- Ensure that the group selected for the Key allows use of
qwen-audio-3.0-tts-plusand that the available balance is sufficient. - Select a voice supported by the current model. This document uses
longanlingxin, which has been successfully used in the formal-environment HTTP tests described here. For other voices, see the official voice list.
The examples use only environment variables or placeholder Keys. An administration-console login Token cannot replace the model invocation Key.
Endpoint and Invocation Methods
| Method | Production Environment Endpoint | Input and Output |
|---|---|---|
| WebSocket bidirectional streaming | wss://api.maitoken.com/api-ws/v1/inference |
Submit text in segments and receive JSON events and binary audio frames |
| HTTP non-real-time | https://api.maitoken.net/api/v1/services/audio/tts/SpeechSynthesizer |
Submit text once and receive JSON containing an audio URL |
Use the complete native path. Do not add /v1, and do not pass the HTTP address directly to a WebSocket client. The WebSocket route for this model is /api-ws/v1/inference, and the model name is provided in the first run-task message.
/api-ws/v1/realtime?model=... belongs to another Qwen-TTS Realtime session protocol that uses events such as session.update. It cannot be mixed with the run-task protocol described in this document. Whether other models are enabled for an account is determined by the model list and Key permissions.
Authentication
Pass the following in the HTTP request headers for the WebSocket handshake or in the HTTP synthesis request headers:
Authorization: Bearer YOUR_MAITOKEN_API_KEYWebSocket does not require X-Api-Resource-Id, X-DashScope-Async, or X-DashScope-SSE. JSON control messages are sent as WebSocket text frames, and audio is received as binary frames.
The browser-native WebSocket constructor cannot set a custom Authorization request header. Web applications should connect through their own server. Do not put the Key in the URL as a substitute for the request header. The Python example below can set the handshake headers directly.
WebSocket Interaction Flow
- Establish a connection with the Key included in the handshake headers.
- Generate a new task UUID and send
run-task. - Wait for the server to return
task-started, then send the text. - Submit the text sequentially using one or more
continue-taskmessages. - After all text has been submitted, send
finish-taskand continue receiving the remaining audio. - Consider the task successfully completed only after receiving
task-finished; handletask-failedas a failure.
All messages for the same task use the same task_id. MaiToken currently allows only one synthesis task per inference connection; establish a new connection for the next synthesis. Do not copy the upstream documentation's method of reusing one connection for multiple tasks.
1. Start a Task: run-task
{ "header": { "action": "run-task", "task_id": "dbe53a5f-257f-4302-a9c1-1cf1d4790b52", "streaming": "duplex" }, "payload": { "task_group": "audio", "task": "tts", "function": "SpeechSynthesizer", "model": "qwen-audio-3.0-tts-plus", "parameters": { "voice": "longanlingxin", "format": "mp3", "sample_rate": 24000 }, "input": {} }}| Parameter | Type | Description |
|---|---|---|
header.action |
string | run-task at startup |
header.task_id |
string | A UUID is generated for each new task and reused in subsequent messages |
header.streaming |
string | Use duplex for bidirectional streaming |
payload.task_group |
string | Fixed as audio |
payload.task |
string | Fixed as tts |
payload.function |
string | Fixed as SpeechSynthesizer |
payload.model |
string | Exact model ID; this document uses qwen-audio-3.0-tts-plus |
payload.parameters.voice |
string | A voice ID supported and accessible by the current model |
payload.parameters.format |
string | This document uses mp3; adjust audio processing accordingly when using another format |
payload.parameters.sample_rate |
integer | This document uses 24000 Hz; refer to the model documentation for the supported range |
payload.input |
object | Pass {} when starting a bidirectional streaming task; submit text through subsequent messages |
The model and voice are determined at startup and cannot be switched in subsequent continue-task requests. Voice permissions depend on the currently available upstream resources; custom voices must first be created and registered through the corresponding voice management API in MaiToken.
2. Submit Text: continue-task
Send the following after receiving task-started:
{ "header": { "action": "continue-task", "task_id": "dbe53a5f-257f-4302-a9c1-1cf1d4790b52", "streaming": "duplex" }, "payload": { "input": { "text": "Hello, welcome to MaiToken." } }}Subsequent text can continue to be sent using messages with the same structure. Sending text in natural short phrases is recommended; production applications must receive audio concurrently to avoid buffer buildup caused by sending without reading. Do not assume that each text submission corresponds exactly to one audio frame.
3. Complete Input: finish-task
{ "header": { "action": "finish-task", "task_id": "dbe53a5f-257f-4302-a9c1-1cf1d4790b52", "streaming": "duplex" }, "payload": { "input": {} }}finish-task indicates that all text has been sent; it does not indicate that all audio has been received. Do not disconnect immediately at this point.
Responses and Audio Reconstruction
| Response content | Meaning and handling |
|---|---|
JSON: header.event=task-started |
The task has started; text can be submitted |
| Binary frame | An audio segment; write it to a file or pass it to a decoder in the order received |
JSON: header.event=result-generated |
A result or usage event during synthesis; read payload as needed |
JSON: header.event=task-finished |
Synthesis completed successfully; the connection can be closed and the file save finalized |
JSON: header.event=task-failed |
Read header.error_code and header.error_message for troubleshooting |
Completion event structure:
{ "header": { "task_id": "dbe53a5f-257f-4302-a9c1-1cf1d4790b52", "event": "task-finished" }, "payload": { "usage": { "characters": 26 } }}The example above shows only the event structure. For the actual fields and the location where usage appears, follow the upstream response. payload.usage.characters is the character usage; the same task may report cumulative values multiple times, so do not add each cumulative value repeatedly.
This article uses MP3, whose binary frames can be concatenated sequentially. Binary frames are not Base64 and do not need to be decoded; JSON control frames must not be written to the audio file. If PCM is used instead, configure the player according to the sample rate, channels, and sample format returned by the model. Do not treat PCM as MP3 or WAV simply by changing the file extension.
Complete Python Example: Receive and Save MP3 as a Stream
Install the dependency:
python -m pip install websocket-clientSave as qwen_tts_stream.py. This example receives and saves audio over WebSocket and does not include audio device playback logic. When a failure occurs, the .part file is retained for inspection; the final MP3 is created only after a successful completion event is received.
import jsonimport osimport timeimport uuidfrom pathlib import Path import websocket def main(): key = os.environ.get("MAITOKEN_API_KEY", "").strip() if not key: raise RuntimeError("Please set MAITOKEN_API_KEY first") task_id = str(uuid.uuid4()) target = Path(f"qwen-{task_id}.mp3") partial = target.with_suffix(".mp3.part") texts = ["Hello, welcome to MaiToken.", "This is an example of real-time Qwen speech synthesis."] started = False finished = False audio_bytes = 0 latest_usage = None ws = websocket.create_connection( "wss://api.maitoken.com/api-ws/v1/inference", header={"Authorization": f"Bearer {key}"}, timeout=30, ) def send(action, payload): ws.send(json.dumps({ "header": { "action": action, "task_id": task_id, "streaming": "duplex", }, "payload": payload, }, ensure_ascii=False)) try: print("Task ID:", task_id) send("run-task", { "task_group": "audio", "task": "tts", "function": "SpeechSynthesizer", "model": "qwen-audio-3.0-tts-plus", "parameters": { "voice": "longanlingxin", "format": "mp3", "sample_rate": 24000, }, "input": {}, }) deadline = time.monotonic() + 120 with partial.open("xb") as output: while not finished: remaining = deadline - time.monotonic() if remaining <= 0: raise TimeoutError("The task exceeded the example's 120-second total timeout") ws.settimeout(min(30, remaining)) frame = ws.recv() if isinstance(frame, bytes): output.write(frame) audio_bytes += len(frame) continue if not frame: raise RuntimeError("The connection closed prematurely without receiving task-finished") event = json.loads(frame) header = event.get("header") or {} if header.get("task_id") not in (None, "", task_id): raise RuntimeError("Received an event belonging to a different task") payload = event.get("payload") or {} usage = payload.get("usage") if isinstance(usage, dict): latest_usage = usage name = header.get("event") if name == "task-started" and not started: started = True # Two short sentences can be submitted immediately. When integrating # continuous LLM output, use separate sending logic, keep this receive # loop running, and send finish-task only after the text ends. for text in texts: send("continue-task", {"input": {"text": text}}) send("finish-task", {"input": {}}) elif name == "task-failed": raise RuntimeError( f"Task failed: {header.get('error_code')}, " f"{header.get('error_message')}" ) elif name == "task-finished": finished = True if not audio_bytes: raise RuntimeError("The task ended but no audio data was received") partial.replace(target) print(f"Saved {target}, {audio_bytes} bytes in total") print("Upstream usage:", latest_usage) finally: ws.close() if __name__ == "__main__": main()Bash / Git Bash:
export MAITOKEN_API_KEY='Replace with your MaiToken API Key'python qwen_tts_stream.pyWindows PowerShell:
$env:MAITOKEN_API_KEY = 'Replace with your MaiToken API Key'python qwen_tts_stream.pyThis example sets a 30-second timeout for each receive operation and a 120-second total task timeout for short-text integration testing. Adjust the timeouts to suit your needs for long-text workloads. A timeout or interruption does not necessarily mean no charges were incurred. Do not retry indefinitely automatically.
Non-real-time HTTP Calls
If you do not need to receive audio as text is being submitted, you can use the HTTP route. Note the parameter locations: for HTTP, voice, format, and sample_rate go in input, unlike payload.parameters in the WebSocket example above.
Bash / cURL
export MAITOKEN_API_KEY='Replace with your MaiToken API Key' curl --fail-with-body --silent --show-error --max-time 120 \ 'https://api.maitoken.net/api/v1/services/audio/tts/SpeechSynthesizer' \ -H "Authorization: Bearer ${MAITOKEN_API_KEY}" \ -H 'Content-Type: application/json; charset=utf-8' \ --data-binary '{"model":"qwen-audio-3.0-tts-plus","input":{"text":"Hello, this is a Qwen text-to-speech test.","voice":"longanlingxin","format":"mp3","sample_rate":24000}}'Frequently Asked Questions
| Issue | Troubleshooting |
|---|---|
| HTTP 401 during handshake | Check that the MaiToken Key is valid and includes Bearer. Do not use the admin login token. |
Model unavailable or task-failed |
Check Key group permissions, the first-frame model ID, voice permissions, and the error message. A successful handshake does not mean the model task succeeded. |
404 or unsupported_endpoint |
Check the complete native path, avoid adding /v1 twice, and distinguish between inference and realtime. |
| No audio after sending text | Confirm that task-started was received; use the same task_id for all frames; send finish-task at the end. |
| Audio is truncated | Do not close the connection immediately after sending finish-task; wait for task-finished. |
| MP3 cannot be played | Concatenate only binary audio frames. Do not write JSON text into the file or Base64-decode binary frames. |
| Changing the model or voice is rejected | Open a new connection and specify it in the new run-task. |
Second run-task is rejected |
MaiToken currently allows only one task per connection. Reconnect for each new task. |
| 429 or concurrency limit | Reduce concurrency and use backoff. If an interruption occurs after audio has been received, do not unconditionally replay the entire task. |
| Character usage differs from text length | Use the upstream characters value. Do not substitute byte count, audio duration, or local string length. |
| Custom voice cannot be used | Check whether it was registered through MaiToken and whether the model used to create the voice matches the current model. |
For supported models and input limits related to SSML, instruction control, and other advanced parameters, follow the Qianwen documentation. The examples in this document use plain text and do not enable these features by default. AOQ mentioned in the Qianwen documentation is not part of the MaiToken integration method verified in this document.
Documentation Basis and Verification Scope
- Qianwen Real-Time Speech Synthesis: Real-time synthesis mode and native WebSocket event flow.
- Current MaiToken Speech Synthesis Documentation: Existing Seed TTS documentation structure and API differences.
- Qianwen Qwen-Audio-TTS Voice List: Reference for voice selection.
- MaiToken gateway routing and WebSocket validation implementation: Confirms inference routing, model selection in the first frame, and the one-task-per-connection limitation.
Verification date: 2026-09-29. Production HTTP requests successfully returned status 200, an audio URL, and usage of 26 characters. No additional paid synthesis requests were made during this round of documentation. The WebSocket example was written based on the official protocol and gateway implementation and underwent static syntax validation, but it was not tested in the production environment. Therefore, successful HTTP verification must not be considered equivalent to WebSocket acceptance.
