Tous les produits
Search
Centre de documentation

Alibaba Cloud Model Studio:Qwen-TTS non-real-time speech synthesis API reference

Dernière mise à jour :Oct 11, 2026

Paramètres de requête et champs de réponse de l'API de synthèse vocale en différé (Qwen-TTS).

Corps de la requête

Sortie non streaming

Python

L'interface SpeechSynthesizer du SDK Python DashScope est désormais unifiée sous MultiModalConversation. Son utilisation et ses paramètres restent entièrement cohérents.

# Install the latest version of the DashScope SDK
import os
import dashscope
# Singapore region
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
text = "Let me recommend a T-shirt to everyone. This one is really super nice. The color is very elegant, and it's also a perfect item to match. Everyone can buy it without hesitation. It's truly beautiful and very forgiving on the figure. No matter what body type you have, it will look great. I recommend everyone to place an order."
# SpeechSynthesizer interface usage: dashscope.audio.qwen_tts.SpeechSynthesizer.call(...)
response = dashscope.MultiModalConversation.call(
    model="qwen3-tts-flash",
    # The API keys for Singapore and Beijing regions are different. Get your API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    text=text,
    voice="Cherry"
)
print(response)

Java

// Install the latest version of the DashScope SDK
    import com.alibaba.dashscope.aigc.multimodalconversation.AudioParameters;
    import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
    import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
    import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
    import com.alibaba.dashscope.exception.ApiException;
    import com.alibaba.dashscope.exception.NoApiKeyException;
    import com.alibaba.dashscope.exception.UploadFileException;
    import com.alibaba.dashscope.utils.JsonUtils;
    import com.alibaba.dashscope.utils.Constants;
    public class Main {
        private static final String MODEL = "qwen3-tts-flash";
        public static void call() throws ApiException, NoApiKeyException, UploadFileException {
            MultiModalConversation conv = new MultiModalConversation();
            MultiModalConversationParam param = MultiModalConversationParam.builder()
                    .model(MODEL)
                    // The API keys for Singapore and Beijing regions are different. Get your API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
                    // If the environment variable is not configured, replace the following line with your Model Studio API key: apiKey("sk-xxx")
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .text("Today is a wonderful day to build something people love!")
                    .voice(AudioParameters.Voice.CHERRY)
                    .parameter("language_type", "English")
                    .build();
            MultiModalConversationResult result = conv.call(param);
            System.out.println(JsonUtils.toJson(result));
        }
        public static void main(String[] args) {
            // Singapore region
            Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
            try {
                call();
            } catch (ApiException | NoApiKeyException | UploadFileException e) {
                System.out.println(e.getMessage());
            }
            System.exit(0);
        }
    }

curl

# ======= IMPORTANT NOTE =======
    # Singapore region
    # The API keys for Singapore and Beijing regions are different. Get your API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # If the environment variable is not configured, replace $DASHSCOPE_API_KEY with your Model Studio API key: sk-xxx.
    # === DELETE THIS COMMENT WHEN EXECUTING ===

    curl -X POST 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
        "model": "qwen3-tts-flash",
        "input": {
            "text": "Let me recommend a T-shirt to everyone. This one is really super nice. The color is very elegant, and it's also a perfect item to match. Everyone can buy it without hesitation. It's truly beautiful and very forgiving on the figure. No matter what body type you have, it will look great. I recommend everyone to place an order.",
            "voice": "Cherry",
            "language_type": "English"
        }
    }'

Sortie streaming

Python

L'interface SpeechSynthesizer du SDK Python DashScope est désormais unifiée sous MultiModalConversation. Pour passer à la nouvelle interface, remplacez simplement le nom ; tous les autres paramètres sont entièrement compatibles.

# DashScope SDK version 1.24.5 or later required
import os
import dashscope
# Singapore region
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
text = "Let me recommend a T-shirt to everyone. This one is really super nice. The color is very elegant, and it's also a perfect item to match. Everyone can buy it without hesitation. It's truly beautiful and very forgiving on the figure. No matter what body type you have, it will look great. I recommend everyone to place an order."
# SpeechSynthesizer interface usage: dashscope.audio.qwen_tts.SpeechSynthesizer.call(...)
response = dashscope.MultiModalConversation.call(
    model="qwen3-tts-flash",
    # The API keys for Singapore and Beijing regions are different. Get your API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    text=text,
    voice="Cherry",
    stream=True
)
for chunk in response:
    print(chunk)

Java

// DashScope SDK version 2.19.0 or later required
    import com.alibaba.dashscope.aigc.multimodalconversation.AudioParameters;
    import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
    import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
    import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
    import com.alibaba.dashscope.exception.ApiException;
    import com.alibaba.dashscope.exception.NoApiKeyException;
    import com.alibaba.dashscope.exception.UploadFileException;
    import com.alibaba.dashscope.utils.JsonUtils;
    import com.alibaba.dashscope.utils.Constants;
    import io.reactivex.Flowable;
    public class Main {
        private static final String MODEL = "qwen3-tts-flash";
        public static void streamCall() throws ApiException, NoApiKeyException, UploadFileException {
            MultiModalConversation conv = new MultiModalConversation();
            MultiModalConversationParam param = MultiModalConversationParam.builder()
                    .model(MODEL)
                    // The API keys for Singapore and Beijing regions are different. Get your API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
                    // If the environment variable is not configured, replace the following line with your Model Studio API key: apiKey("sk-xxx")
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .text("Today is a wonderful day to build something people love!")
                    .voice(AudioParameters.Voice.CHERRY)
                    .parameter("language_type", "English")
                    .build();
            Flowable<MultiModalConversationResult> result = conv.streamCall(param);
            result.blockingForEach(r -> {System.out.println(JsonUtils.toJson(r));
            });
        }
        public static void main(String[] args) {
            // Singapore region
            Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
            try {
                streamCall();
            } catch (ApiException | NoApiKeyException | UploadFileException e) {
                System.out.println(e.getMessage());
            }
            System.exit(0);
        }
    }

curl

# ======= IMPORTANT NOTE =======
    # Singapore region
    # The API keys for Singapore and Beijing regions are different. Get your API Key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # If the environment variable is not configured, replace $DASHSCOPE_API_KEY with your Model Studio API key: sk-xxx.
    # === DELETE THIS COMMENT WHEN EXECUTING ===

    curl -X POST 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -H 'X-DashScope-SSE: enable' \
    -d '{
        "model": "qwen3-tts-flash",
        "input": {
            "text": "Let me recommend a T-shirt to you. This one is truly stunning. Its color highlights your elegance and makes it an ideal match for any outfit. You can buy it without hesitation - it looks great on everyone. It flatters all body types. Whether you're tall, short, slim, or curvy, this T-shirt suits you perfectly. We highly recommend ordering it.",
            "voice": "Cherry",
            "language_type": "English"
        }
    }'

Pour lire en temps réel l’audio encodé en Base64, consultez Lecture en streaming.

modelstring(obligatoire)

Nom du modèle. Pour plus de détails, consultez Modèles pris en charge.

inputobject(obligatoire)

Paramètres d'entrée.

Propriétés

text string (obligatoire)

Texte à synthétiser. Prend en charge les entrées mixtes multilingues. La longueur maximale d'entrée est de 600 caractères.

voice string (obligatoire)

Voix à utiliser. Consultez Voix système prises en charge.

language_type string (facultatif)

Langue de l'audio synthétisé. La valeur par défaut est Auto.

  • Auto : À utiliser lorsque l'entrée contient plusieurs langues ou que la langue ne peut être déterminée. Le modèle adapte automatiquement la prononciation pour chaque segment linguistique, bien que la précision ne soit pas garantie.

  • Langue spécifique : À utiliser pour un texte monolingue. Spécifier la langue améliore considérablement la qualité de la synthèse et produit généralement de meilleurs résultats que Auto. Valeurs valides :

    • Chinese
    • English
    • German
    • Italian
    • Portuguese
    • Spanish
    • Japanese
    • Korean
    • French
    • Russian

Objet de réponse (les formats streaming et non streaming sont identiques)

{
    "status_code": 200,
    "request_id": "5c63c65c-cad8-4bf4-959d-xxxxxxxxxxxx",
    "code": "",
    "message": "",
    "output": {
        "text": null,
        "finish_reason": "stop",
        "choices": null,
        "audio": {
            "data": "",
            "url": "http://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/1d/ab/20251218/d2033070/39b6d8f2-c0db-4daa-9073-5d27bfb66b78.wav?Expires=1766113409&OSSAccessKeyId=YOUR_ACCESS_KEY_ID&Signature=YOUR_SIGNATURE",
            "id": "audio_5c63c65c-cad8-4bf4-959d-xxxxxxxxxxxx",
            "expires_at": 1766113409
        }
    },
    "usage": {
        "input_tokens": 0,
        "output_tokens": 0,
        "characters": 195
    }
}

status_code integer

Code de statut HTTP tel que défini dans la RFC 9110. Valeurs courantes :
• 200 : Requête réussie.
• 400 : Paramètres de requête invalides.
• 401 : Non autorisé.
• 404 : Ressource introuvable.
• 500 : Erreur interne du serveur.

request_id string

Identifiant unique de cette requête. Utilisez-le pour le dépannage.

code string

Code d'erreur retourné en cas d'échec. Consultez Codes d'erreur.

message string

Message d'erreur retourné en cas d'échec. Consultez Codes d'erreur.

outputobject

Sortie du modèle.

Propriétés

textstring

Toujours null. Ignorez ce champ.

choicesstring

Toujours null. Ignorez ce champ.

finish_reasonstring

État de la génération :

  • null — Génération en cours.
  • stop — Génération terminée normalement ou condition d'arrêt atteinte.

audio object

Sortie audio du modèle.

Propriétés

url string

URL du fichier audio complet, valable 24 heures. En mode non streaming, elle est retournée directement dans la réponse. En mode streaming, elle n'est retournée que dans le dernier chunk du flux SSE (les chunks intermédiaires ne contiennent pas ce champ).

data string

Données audio encodées en Base64. En mode non streaming, ce champ est toujours une chaîne vide (utilisez url pour obtenir le fichier audio complet). En mode streaming, les chunks intermédiaires contiennent des segments audio encodés en Base64, tandis que le dernier chunk retourne une chaîne vide (utilisez url pour obtenir l'audio complet).

id string

Identifiant unique de l'audio.

expires_at integer

Heure d'expiration de l'URL sous forme de timestamp Unix.

usage object

Utilisation des caractères pour cette requête.

Propriétés

output_tokens integer

Nombre de tokens consommés par l'audio de sortie. Pour le modèle Qwen3-TTS-Flash, ce champ est toujours égal à 0.

input_tokens integer

Nombre de tokens consommés par le texte d'entrée. Pour le modèle Qwen3-TTS-Flash, ce champ est toujours égal à 0.

characters integer

Nombre de caractères dans le texte d'entrée. Retourné uniquement par le modèle Qwen3-TTS-Flash.

request_id string

Identifiant unique de cette requête. Utilisez-le pour le dépannage.

Téléchargement et lecture audio

Avant d’exécuter les exemples, obtenez et configurez une clé API et installez le SDK DashScope. L’exemple de lecture en Python nécessite également PyAudio et NumPy. Consultez les commentaires du code pour installer PyAudio et installez NumPy avec pip install numpy.

Télécharger un fichier audio (Java)

L'importation de la dépendance Gson est requise. Utilisez Maven ou Gradle pour l'ajouter :

Maven

Ajoutez cet extrait à votre fichier pom.xml :

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.13.1</version>
</dependency>

Gradle

Ajoutez la ligne ci-après dans build.gradle :

// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation("com.google.code.gson:gson:2.13.1")
import com.alibaba.dashscope.aigc.multimodalconversation.AudioParameters;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

public class Main {
    private static final String MODEL = "qwen3-tts-flash";
    public static void call() throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // The API Keys for the Singapore and Beijing regions are different. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
                // If you have not configured the environment variable, replace the following line with your Model Studio API Key: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model(MODEL)
                .text("Today is a wonderful day to build something people love!")
                .voice(AudioParameters.Voice.CHERRY)
                .languageType("English") // We recommend matching this with the language of the text for correct pronunciation and natural intonation.
                .build();
        MultiModalConversationResult result = conv.call(param);
        String audioUrl = result.getOutput().getAudio().getUrl();
        System.out.print(audioUrl);

        // Download the audio file to local storage
        try (InputStream in = new URL(audioUrl).openStream();
             FileOutputStream out = new FileOutputStream("downloaded_audio.wav")) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            System.out.println("\nAudio file downloaded to: downloaded_audio.wav");
        } catch (Exception e) {
            System.out.println("\nFailed to download audio file: " + e.getMessage());
        }
    }
    public static void main(String[] args) {
        // The following is the configuration for the Singapore region.
        Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
        try {
            call();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

Lecture en streaming

Python

# coding=utf-8
#
# Installation instructions for pyaudio:
# APPLE Mac OS X
#   brew install portaudio
#   pip install pyaudio
# Debian/Ubuntu
#   sudo apt-get install python-pyaudio python3-pyaudio
#   or
#   pip install pyaudio
# CentOS
#   sudo yum install -y portaudio portaudio-devel && pip install pyaudio
# Microsoft Windows
#   python -m pip install pyaudio

import os
import dashscope
import pyaudio
import time
import base64
import numpy as np

# The following is the configuration for the Singapore region.
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

p = pyaudio.PyAudio()
# Create an audio stream
stream = p.open(format=pyaudio.paInt16,
                channels=1,
                rate=24000,
                output=True)

text = "Today is a wonderful day to build something people love!"
response = dashscope.MultiModalConversation.call(
    # The API Keys for the Singapore and Beijing regions are different. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    # If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key = "sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen3-tts-flash",
    text=text,
    voice="Cherry",
    language_type="English", # We recommend matching this with the language of the text for correct pronunciation and natural intonation.
    stream=True
)

for chunk in response:
    if chunk.output is not None:
      audio = chunk.output.audio
      if audio.data is not None:
          wav_bytes = base64.b64decode(audio.data)
          audio_np = np.frombuffer(wav_bytes, dtype=np.int16)
          # Play audio data directly
          stream.write(audio_np.tobytes())
      if chunk.output.finish_reason == "stop":
          print(f"finish at: {chunk.output.audio.expires_at}")
time.sleep(0.8)
# Clean up resources
stream.stop_stream()
stream.close()
p.terminate()

Java

Assurez-vous d'importer la dépendance Gson en l'ajoutant via Maven ou Gradle :

Maven

Déclarez la dépendance suivante dans pom.xml :

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.13.1</version>
</dependency>

Gradle

Renseignez cette ligne dans build.gradle :

// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation("com.google.code.gson:gson:2.13.1")
// Please install the latest version of the DashScope SDK
import com.alibaba.dashscope.aigc.multimodalconversation.AudioParameters;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import io.reactivex.Flowable;
import javax.sound.sampled.*;
import java.util.Base64;

public class Main {
    private static final String MODEL = "qwen3-tts-flash";
    public static void streamCall() throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // The API Keys for the Singapore and Beijing regions are different. Get an API Key: https://www.alibabacloud.com/help/zh/model-studio/get-api-key
                // If you have not configured the environment variable, replace the following line with your Model Studio API Key: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model(MODEL)
                .text("Today is a wonderful day to build something people love!")
                .voice(AudioParameters.Voice.CHERRY)
                .languageType("English") // We recommend matching this with the language of the text for correct pronunciation and natural intonation.
                .build();
        Flowable<MultiModalConversationResult> result = conv.streamCall(param);
        result.blockingForEach(r -> {
            try {
                // 1. Get the Base64-encoded audio data
                String base64Data = r.getOutput().getAudio().getData();
                byte[] audioBytes = Base64.getDecoder().decode(base64Data);

                // 2. Configure the audio format (adjust according to the audio format returned by the API)
                AudioFormat format = new AudioFormat(
                        AudioFormat.Encoding.PCM_SIGNED,
                        24000, // Sample rate (must match the format returned by the API)
                        16,    // Bit depth
                        1,     // Number of channels
                        2,     // Frame size (in bytes)
                        24000, // Frame rate (must match the sample rate)
                        false  // Big-endian
                );

                // 3. Play audio data in real time
                DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
                try (SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info)) {
                    if (line != null) {
                        line.open(format);
                        line.start();
                        line.write(audioBytes, 0, audioBytes.length);
                        line.drain();
                    }
                }
            } catch (LineUnavailableException e) {
                e.printStackTrace();
            }
        });
    }
    public static void main(String[] args) {
        // The following is the configuration for the Singapore region.
        Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
        try {
            streamCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}