HTTP API

Updated at:

This API converts text to speech using the Qwen-Audio-3.0-TTS-Plus model through an HTTP POST request and returns an audio download URL. It supports use cases such as audiobooks, course voice-overs, and content production.

Features

  • Non-streaming synthesis: Submit text to receive a URL for downloading the synthesized audio file.

  • Voice selection: Specify a voice name to select a speaker. You can also synthesize speech using reference audio, as shown in the use case example below.

Prerequisites

Speech synthesis is available in trial and commercial editions. For billing details, see Billing items. To upgrade from the trial edition to the commercial edition, see Billing.

Endpoint

The gateway URL for the China (Beijing) region is https://nls-gateway-cn-beijing.aliyuncs.com. Use the following HTTP method and URL:

POST https://nls-gateway-cn-beijing.aliyuncs.com/rest/v1/general/SpeechSynthesizer?appkey={appkey}

Code examples

The examples read the Appkey and NLS token from the NLS_APP_KEY and NLS_TOKEN environment variables. The Python examples require requests, which you can install with pip install requests.

cURL

curl -X POST "https://nls-gateway-cn-beijing.aliyuncs.com/rest/v1/general/SpeechSynthesizer?appkey=${NLS_APP_KEY}" \
  -H "Content-Type: application/json" \
  -H "X-NLS-Token: ${NLS_TOKEN}" \
  -d '{
    "text": "Hello, welcome to use our voice synthesis system.",
    "voice": "sarah"
  }'

Parse the data field in the response as JSON, then download the audio from its url field.

Python

import json
import os
from pathlib import Path

import requests

BASE_URL = "https://nls-gateway-cn-beijing.aliyuncs.com"
APPKEY = os.environ["NLS_APP_KEY"]
TOKEN = os.environ["NLS_TOKEN"]


def synthesize_audio(text, voice="sarah"):
    response = requests.post(
        f"{BASE_URL}/rest/v1/general/SpeechSynthesizer",
        params={"appkey": APPKEY},
        headers={"X-NLS-Token": TOKEN},
        json={"text": text, "voice": voice},
        timeout=120,
    )
    try:
        result = response.json()
    except ValueError:
        response.raise_for_status()
        raise RuntimeError("Unexpected non-JSON response")
    if response.status_code != 200 or result.get("error_code") != 0:
        raise RuntimeError(
            f"Synthesis failed: {result.get('error_code')} "
            f"{result.get('error_message')}; request_id={result.get('request_id')}"
        )

    audio_url = json.loads(result["data"])["url"]
    audio_response = requests.get(audio_url, timeout=60)
    audio_response.raise_for_status()
    Path("output.wav").write_bytes(audio_response.content)
    print("Audio saved to output.wav")


if __name__ == "__main__":
    synthesize_audio("Hello, welcome to use our voice synthesis system.")

Use case: Synthesize speech using reference audio

This Python example specifies reference audio through prompt_wav_url without passing voice. It synthesizes the text and saves the audio locally. The reference audio URL must be publicly accessible. Parse the response in the same way as for a synthesis request that specifies a voice.

import json
import os
from pathlib import Path

import requests

BASE_URL = "https://nls-gateway-cn-beijing.aliyuncs.com"
APPKEY = os.environ["NLS_APP_KEY"]
TOKEN = os.environ["NLS_TOKEN"]


def synthesize_audio(text, prompt_wav_url):
    response = requests.post(
        f"{BASE_URL}/rest/v1/general/SpeechSynthesizer",
        params={"appkey": APPKEY},
        headers={"X-NLS-Token": TOKEN},
        json={"text": text, "prompt_wav_url": prompt_wav_url},
        timeout=120,
    )
    try:
        result = response.json()
    except ValueError:
        response.raise_for_status()
        raise RuntimeError("Unexpected non-JSON response")
    if response.status_code != 200 or result.get("error_code") != 0:
        raise RuntimeError(
            f"Synthesis failed: {result.get('error_code')} "
            f"{result.get('error_message')}; request_id={result.get('request_id')}"
        )

    audio_url = json.loads(result["data"])["url"]
    audio_response = requests.get(audio_url, timeout=60)
    audio_response.raise_for_status()
    Path("output.wav").write_bytes(audio_response.content)
    print("Audio saved to output.wav")


if __name__ == "__main__":
    synthesize_audio(
        "Hello, welcome to use our voice synthesis system.",
        "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen3-TTS-Repo/clone.wav",
    )

Request details

Request headers

Parameter

Type

Required

Description

Content-Type

String

Yes

The media type of the request body. Set this parameter to application/json.

X-NLS-Token

String

Yes

The NLS access token.

Request parameters

Parameter

Type

Required

Description

appkey

String

Yes

The project Appkey obtained from the console.

Request body

The following parameters apply to synthesis requests that specify a voice.

Parameter

Type

Required

Description

text

String

Yes

The text to synthesize, up to 500 characters.

voice

String

Yes

The speaker identifier. For valid values, see Supported voices.

format

String

No

The output audio format. Default: wav. The API currently returns WAV audio. This parameter does not change the output format. For another format, convert the audio after downloading it.

sample_rate

Integer

No

The audio sample rate in Hz. Default: 24000. The API currently returns 24000 Hz audio. This parameter does not change the output sample rate. For another sample rate, resample the audio after downloading it.

Example request body:

{
    "text": "Hello, welcome to use our voice synthesis system.",
    "voice": "sarah",
    "format": "wav",
    "sample_rate": 24000
}

Response body

Parameter

Type

Description

status

Integer

The HTTP status code. A value of 200 indicates success.

error_code

Integer

The service error code. A value of 0 indicates success.

error_message

String

The error description. This field is an empty string on success.

request_id

String

The unique request ID for troubleshooting.

data

String

The synthesis result returned on success. This is a JSON-encoded string that requires a second JSON parsing step.

url

String

The API path returned when the request fails.

The data field

Parameter

Type

Description

url

String

The download URL for the synthesized audio file. It is valid for 24 hours. After it expires, call the API again to generate a new URL.

Success response

The audio URL in this example is a placeholder.

{
    "status": 200,
    "data": "{\"url\":\"https://example.com/output.wav\"}",
    "request_id": "3f9667fbfc594d87ab1afa950647c5db",
    "error_code": 0,
    "error_message": ""
}

Error response

The following error is returned when the Appkey is missing:

{
    "error_message": "Gateway:CLIENT_ERROR:Required String parameter 'appkey' is not present",
    "error_code": 40000000,
    "request_id": "b600c23af0ed4d43a7ce836b4fe59793",
    "url": "/rest/v1/general/SpeechSynthesizer",
    "status": 400
}

Supported voices

Voice

Description

sarah

Female, American English

seline

Female, American English

megan

Female, British English

isabella

Female, British English

davis

Male, American English

michael

Male, American English

arthur

Male, British English

barry

Male, British English

sophie

Female, British English

grace

Female, British English

winston

Male, British English

edmund

Male, British English

paige

Female, American English

avery

Female, American English

hunter

Male, American English

mason

Male, American English

Error codes

The following table lists common error codes and their solutions.

HTTP status code

error_code

Description

Solution

400

40000000

A parameter error, such as a missing Appkey. See error_message for the specific cause.

Check appkey in the URL and the request parameters.

400

40000001

The token is invalid.

Obtain a new, valid NLS token.

500

50020003

The specified voice was not found.

Check that voice is one of the supported voices listed in this topic.

400

500

The synthesis request failed.

Check the parameters required for the selected synthesis method.

500

50000000

A server-side error occurred.

Retry the request. If the error persists, retain request_id and contact technical support.

The following table lists solutions for other HTTP errors.

HTTP status code

Solution

403

Check that the Appkey and token match.

429

Reduce the request rate or request a quota increase.

503

Retry later.

FAQ

How long is the audio URL valid?

The audio URL is valid for 24 hours after it is generated. After it expires, call the API again to generate a new URL.

Is there a text length limit?

The text in a single request must not exceed 500 characters. For longer text, we recommend splitting it into segments for synthesis.