QwenCloudBRASIL
Tradução de apoio para consulta. Código e identificadores técnicos preservados. Consultar referência original ↗

Síntese de fala não em tempo real

Síntese de fala não em tempo real com Qwen3-TTS

A síntese de fala não em tempo real converte texto em fala (TTS) através de uma API HTTP. Ele se encaixa em cenários tolerantes à latência, como produção de audiolivros, narração eletrônica e produção de conteúdo.

Visão geral

Converta texto completo para arquivos de fala através de uma API HTTP. Dois modos de saída estão disponíveis: não-streaming e streaming.

Para síntese de baixa latência, veja [Síntese de fala em tempo real]/developer-guides/speech/realtime-streaming). Para escolher um modelo, veja [Modelos de texto para fala] (/developer-guides/speech/tts-models).

Pré-requisitos

-Começo rápido.

Os exemplos a seguir demonstram como sintetizar a fala com o Qwen3-TTS Modelo. Para descrições detalhadas dos parâmetros, veja a [referência da API] (#api-reference).

Use a voz do sistema.

Use uma [voz incorporada] (#built-in-voices) para síntese de fala.

** Não-streaming saída **

Use o retornado. url para recuperar o áudio sintetizado. A URL é válida por 24 horas.

Você deve importar a dependência Gson para Java. Se você usar Maven ou Gradle, adicione a dependência como segue:

Maven

 Adicione o seguinte conteúdo para `pom.xml`:

```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

 Adicione o seguinte conteúdo para `build.gradle`:

```gradle
// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation("com.google.code.gson:gson:2.13.1")
```
import os
import dashscope

dashscope.base_http_api_url = 'https://maas.qwencloudapi.com/api/v1'

text = "Today is a wonderful day to build something people love!"
# To use the SpeechSynthesizer interface: dashscope.audio.qwen_tts.SpeechSynthesizer.call(...)
response = dashscope.MultiModalConversation.call(
  model="qwen3-tts-flash",
  # If you have not configured an environment variable, replace the following line with your API key: api_key = "sk-xxx"
  api_key=os.getenv("DASHSCOPE_API_KEY"),
  text=text,
  voice="Cherry",
  language_type="English", # We recommend that this matches the text language to ensure correct pronunciation and natural intonation.
  stream=False
)
print(response)
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.protocol.Protocol;
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()
        // If you have not configured an environment variable, replace the following line with your 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 that this matches the text language to ensure 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 locally
    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 local path: downloaded_audio.wav");
    } catch (Exception e) {
      System.out.println("\nError downloading audio file: " + e.getMessage());
    }
  }
  public static void main(String[] args) {
    Constants.baseHttpApiUrl = "https://maas.qwencloudapi.com/api/v1";
    try {
      call();
    } catch (ApiException | NoApiKeyException | UploadFileException e) {
      System.out.println(e.getMessage());
    }
    System.exit(0);
  }
}
curl -X POST 'https://maas.qwencloudapi.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": "Today is a wonderful day to build something people love!",
    "voice": "Cherry",
    "language_type": "English"
  }
}'

? Streaming saída ?

Transmita dados de áudio em formato Base64. O último pacote contém a URL do arquivo de áudio completo.

# 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

dashscope.base_http_api_url = 'https://maas.qwencloudapi.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(
  # If you have not configured an environment variable, replace the following line with your 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 that this matches the text language to ensure 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 the audio data directly
          stream.write(audio_np.tobytes())
      if chunk.output.finish_reason == "stop":
          print("finish at: {} ", chunk.output.audio.expires_at)
time.sleep(0.8)
# Clean up resources
stream.stop_stream()
stream.close()
p.terminate()
// 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.protocol.Protocol;
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()
        // If you have not configured an environment variable, replace the following line with your 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 that this matches the text language to ensure 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 based on the 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,    // Audio bit depth
            1,     // Number of sound channels
            2,     // Frame size (bit depth / 8)
            24000, // Data transfer rate (must match the sample rate)
            false  // Is compressed
        );

        // 3. Play the 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) {
    Constants.baseHttpApiUrl = "https://maas.qwencloudapi.com/api/v1";
    try {
      streamCall();
    } catch (ApiException | NoApiKeyException | UploadFileException e) {
      System.out.println(e.getMessage());
    }
    System.exit(0);
  }
}
curl -X POST 'https://maas.qwencloudapi.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": "Today is a wonderful day to build something people love!",
    "voice": "Cherry",
    "language_type": "English"
  }
}'

Use Voz Clonada.

Para clonagem de voz, veja [clonografia de voz] (/developer-guides/speech/voice-cloning).

Use Voz Projetada.

Para design de voz, veja [Design de voz] (/developer-guides/speech/voice-design).

Controle de instruções.

Controle o tom, velocidade, emoção e timbre usando instruções de linguagem natural em vez de parâmetros de áudio.

CosyVoice (cosyvoice-v3.5-plus, cosyvoice-v3.5-flash-Apóia o controle de instruções. Para detalhes do modelo, veja [Modelos de texto para fala] (/developer-guides/speech/tts-models) e [CosyVoice "Lista de voz" (/developer-guides/speech/voice-list/cosyvoice).

Cenários:

Escrevendo descrições de som de alta qualidade

Princípios da core

  1. Use palavras descritivas como "profundo", "periculoso" ou "rápido", evite palavras vagas como "legal" ou "normal".
  2. Combine múltiplas dimensões, como pitch, velocidade e emoção. Descrições de dimensão única, como "altos" são muito amplas.
  3. Foque-se em características físicas e perceptuais, não em preferências pessoais. Use "alto e energético" em vez de "meu som favorito".
  4. Seja original, descreva qualidades sonoras em vez de pedir imitação de pessoas específicas. O modelo não suporta imitação direta.
  5. Seja conciso, certifique-se de que cada palavra sirva a um propósito. Evite sinônimos repetitivos ou intensificadores sem sentido.

Você pode combinar múltiplas dimensões para criar efeitos de áudio mais ricos.

Dimensão Exemplo
Pitch Alto, médio, baixo, alto, baixo, baixo
Velocidade Rápido, médio, lento, acelerado, lento, lento
Emoção Alegre, calmo, gentil, sério, animado, composto, calmante
Características Magnético, crocante, rouco, suave, doce, profundo, poderoso
Uso Notícias, publicidade, audiolivro, animação, assistente de voz, narração de documentários

*Exemplos *

Personalização de voz

Para criação de voz personalizada, veja/developer-guides/speech/voice-cloning) e [design de voz] (/developer-guides/speech/voice-design).

Referência da API

Vozes embutidas

Veja.Qwen3-TTS "Lista de voz" (/developer-guides/speech/voice-list/qwen-tts) para a lista de vozes apoiadas, compatibilidade de modelos e amostras de áudio.

FAQ

Quanto tempo o URL do arquivo de áudio é válido?

O URL do arquivo de áudio expira após 24 horas.

Saiba mais.