Skip to content

Audio (TTS / ASR / Realtime)

client.audio() groups the speech resources: tts() (synthesis), asr() (recognition), realtime() (spoken dialog over WebSocket), plus voices(), vocabularies(), phrases() and voiceDesign(). TingWu meeting transcription lives at client.tingwu(). All snippets are adapted from the runnable audio examples.

Under development

The client.audio() module is still under development; interfaces may change in future releases (matching the Javadoc of the com.alibaba.dashscope.audio package; client.tingwu() is not affected). Watch for API changes on this page when upgrading the SDK.

Text-to-speech

One-shot HTTP synthesis returns the whole audio as bytes (raw PCM when format("pcm")); prefer the streaming variant for long text:

import com.alibaba.dashscope.types.audio.TtsSynthesizeParams;

byte[] pcm = client.audio().tts().http().synthesize(
    TtsSynthesizeParams.builder()
        .model("qwen-audio-3.1-tts-flash")
        .voice("longanhuan_v3.1")
        .text("Hello from DashScope")
        .format("pcm")          // raw PCM; wrap into WAV yourself if needed
        .sampleRate(24000)
        .build());
  • tts().stream(params) → ResponseStream<byte[]> — incremental audio over HTTP.
  • tts().connect(TtsConnectParams) → SynthesisSession — WebSocket synthesis for incremental text input.

Examples: TtsHttpSynthesize, TtsHttpStreamSynthesize, TtsWebsocketConnect.

Full runnable example: TtsHttpSynthesize.java (auto-synced)
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.examples.atomic.audio;

import com.alibaba.dashscope.DashScopeClient;
import com.alibaba.dashscope.examples.ExampleSupport;
import com.alibaba.dashscope.types.audio.TtsSynthesizeParams;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * HTTP one-shot TTS: synthesize the whole text in one call, wrap the returned raw PCM into one WAV,
 * save it, then play it (unless {@code --no-play}). Default model {@code qwen-audio-3.1-tts-flash}
 * with voice {@code longanhuan_v3.1} at 24000 Hz. A real request may incur charges. The one-shot
 * aggregate holds the whole audio in memory; prefer the streaming variant for long text. Usage:
 *
 * <pre>TtsHttpSynthesize &lt;text&gt; &lt;output.wav&gt; [--model M] [--voice V] [--no-play]</pre>
 *
 * Translation of the Python blueprint example 01_atomic_capabilities/audio/tts_http.py.
 */
public final class TtsHttpSynthesize {

  private static final int SAMPLE_RATE = 24000;

  public static void main(String[] args) throws Exception {
    if (args.length < 2) {
      usage();
      System.exit(2);
    }
    String text = args[0];
    Path output = Paths.get(args[1]);
    String model = "qwen-audio-3.1-tts-flash";
    String voice = "longanhuan_v3.1";
    boolean play = true;
    for (int i = 2; i < args.length; i++) {
      switch (args[i]) {
        case "--model":
          model = value(args, ++i);
          break;
        case "--voice":
          voice = value(args, ++i);
          break;
        case "--no-play":
          play = false;
          break;
        default:
          usage();
          System.exit(2);
      }
    }
    if (text.trim().isEmpty()) {
      System.err.println("error: text must not be empty or blank");
      System.exit(2);
    }

    byte[] pcm;
    try (DashScopeClient client = ExampleSupport.client()) {
      // The aggregated byte[] result carries no requestId/usage; only the streaming variants
      // expose per-frame envelopes.
      pcm =
          client
              .audio()
              .tts()
              .http()
              .synthesize(
                  TtsSynthesizeParams.builder()
                      .model(model)
                      .voice(voice)
                      .text(text)
                      // Request raw PCM: this example wraps it into a WAV itself below.
                      .format("pcm")
                      .sampleRate(SAMPLE_RATE)
                      .build());
    }
    if (pcm.length >= 12
        && pcm[0] == 'R'
        && pcm[1] == 'I'
        && pcm[2] == 'F'
        && pcm[3] == 'F'
        && pcm[8] == 'W'
        && pcm[9] == 'A'
        && pcm[10] == 'V'
        && pcm[11] == 'E') {
      // The service returned a RIFF/WAVE container instead of raw PCM; refuse to wrap it twice.
      throw new IllegalStateException("service returned a WAV container, not raw PCM");
    }
    if (pcm.length == 0 || pcm.length % 2 != 0) {
      throw new IllegalStateException(
          "returned PCM audio is empty or not an even number of bytes (" + pcm.length + ")");
    }
    // Never overwrites an existing file (AudioCommon.writeWav enforces this).
    AudioCommon.writeWav(output, pcm, SAMPLE_RATE);
    System.out.printf(
        "Saved %s (%d bytes PCM, %.2f seconds)%n",
        output.toAbsolutePath(), pcm.length, pcm.length / 2.0 / SAMPLE_RATE);
    if (play) {
      AudioCommon.play(output);
    }
  }

  private static String value(String[] args, int i) {
    if (i >= args.length) {
      usage();
      System.exit(2);
    }
    return args[i];
  }

  private static void usage() {
    System.err.println(
        "usage: TtsHttpSynthesize <text> <output.wav> [--model M] [--voice V] [--no-play]");
  }
}

Speech recognition

Realtime recognition opens a RecognitionSession: send paced audio frames on one thread while iterating results() on another:

import com.alibaba.dashscope.resources.audio.RecognitionSession;
import com.alibaba.dashscope.types.audio.AsrRecognizeParams;
import com.alibaba.dashscope.types.audio.AsrResult;

RecognitionSession session = client.audio().asr().recognize(
    AsrRecognizeParams.builder()
        .model("qwen-audio-3.1-asr-flash-streaming")
        .format("pcm")
        .sampleRate(16000)
        .build());
try {
  session.start();
  // receiver thread: for (AsrResult r : session.results()) { r.getSentence().getText(); ... }
  for (byte[] frame : pcmChunks) {   // pace ~100 ms of audio per frame
    session.sendAudioFrame(frame);
  }
  session.stop();
} finally {
  session.close();
}

AsrResult.Sentence.getSentenceEnd() distinguishes final sentences from partials; session.getRequestId() and getFirstPackageDelay() support diagnostics (the delay stays null when nothing was recognized).

For file transcription, asr().transcribe(AsrTranscribeParams) submits an async Job (asr().jobs() to wait/fetch). Examples: AsrWebsocketRecognize, AsrHttpStreamRecognize, AsrMicrophoneRecognize, AsrJobsTranscribe.

Full runnable example: AsrWebsocketRecognize.java (auto-synced)
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.examples.atomic.audio;

import com.alibaba.dashscope.DashScopeClient;
import com.alibaba.dashscope.examples.ExampleSupport;
import com.alibaba.dashscope.resources.audio.AudioPacer;
import com.alibaba.dashscope.resources.audio.RecognitionSession;
import com.alibaba.dashscope.types.audio.AsrRecognizeParams;
import com.alibaba.dashscope.types.audio.AsrResult;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * WebSocket duplex ASR (translation of the Python blueprint's {@code asr_websocket.py}): send PCM
 * from a local WAV while receiving sentences. Default model {@code
 * qwen-audio-3.1-asr-flash-streaming}; input must be mono 16-bit 16 kHz PCM WAV (no resampling).
 * Usage:
 *
 * <pre>
 * mvn -q -f examples/pom.xml exec:java -Dexec.mainClass=com.alibaba.dashscope.examples.atomic.audio.AsrWebsocketRecognize -Dexec.args="speech.wav"
 * </pre>
 */
public final class AsrWebsocketRecognize {

  public static void main(String[] args) throws Exception {
    if (args.length < 1) {
      System.err.println("usage: AsrWebsocketRecognize <speech.wav> [model]");
      System.exit(2);
    }
    Path wav = Paths.get(args[0]);
    String model = args.length > 1 ? args[1] : "qwen-audio-3.1-asr-flash-streaming";

    AudioCommon.PcmAudio audio = AudioCommon.readWav(wav, 16000);
    int chunkBytes = AudioPacer.bytesPer100ms(audio.sampleRate);

    try (DashScopeClient client = ExampleSupport.client()) {
      RecognitionSession session =
          client
              .audio()
              .asr()
              .recognize(
                  AsrRecognizeParams.builder()
                      .model(model)
                      .format("pcm")
                      .sampleRate(audio.sampleRate)
                      .build());
      ExecutorService receiverPool = Executors.newSingleThreadExecutor();
      try {
        session.start();
        // Receive on a worker thread while the caller thread paces uplink frames.
        Future<?> receiver =
            receiverPool.submit(
                () -> {
                  for (AsrResult result : session.results()) {
                    AsrResult.Sentence sentence = result.getSentence();
                    if (sentence == null || sentence.getText() == null) {
                      continue;
                    }
                    if (Boolean.TRUE.equals(sentence.getSentenceEnd())) {
                      System.out.println(sentence.getText());
                    } else {
                      System.err.println("[partial] " + sentence.getText());
                    }
                  }
                });
        long start = System.nanoTime();
        int index = 0;
        for (byte[] frame : AudioPacer.pcmChunks(audio.pcm, chunkBytes)) {
          AudioPacer.pace(start, index++);
          session.sendAudioFrame(frame);
        }
        session.stop();
        receiver.get();
      } finally {
        session.close();
        receiverPool.shutdown();
      }
      // getFirstPackageDelay() stays null when no sentence was ever recognized (silence or
      // speech-free audio), so it must not be dereferenced unconditionally.
      Duration firstDelay = session.getFirstPackageDelay();
      System.err.println(
          "request_id="
              + session.getRequestId()
              + " first_package_delay_ms="
              + (firstDelay == null ? "null" : firstDelay.toMillis())
              + " usage="
              + session.getUsage());
    }
  }
}

Realtime spoken dialog

realtime().connect(RealtimeParams) opens a RealtimeSession (WebSocket). Configure the session, append audio, then commit and request a response; a single receiver thread consumes events():

import com.alibaba.dashscope.resources.audio.RealtimeSession;
import com.alibaba.dashscope.types.audio.RealtimeParams;
import com.alibaba.dashscope.types.audio.UpdateSessionParams;

RealtimeSession session = client.audio().realtime().connect(
    RealtimeParams.builder().model("qwen-audio-3.0-realtime-plus").build());
try {
  session.connect();
  session.updateSession(UpdateSessionParams.builder()
      .modalities(Arrays.asList("text", "audio"))
      .voice("longanqian")
      .inputAudioFormat("pcm")
      .outputAudioFormat("pcm")
      .enableTurnDetection(false)   // manual end-of-turn: commit + createResponse
      .build());
  // receiver thread iterates session.events() (single-use stream)
  session.appendAudio(pcmFrame);
  session.commit();
  session.createResponse();
} finally {
  session.close();
}

Examples: RealtimeQwenAudioDialog (Qwen-Audio dialect), RealtimeOmniDialog (omni), RealtimeTranslation (live translate).

Full runnable example: RealtimeQwenAudioDialog.java (auto-synced)
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.examples.atomic.audio;

import com.alibaba.dashscope.DashScopeClient;
import com.alibaba.dashscope.examples.ExampleSupport;
import com.alibaba.dashscope.resources.audio.RealtimeSession;
import com.alibaba.dashscope.types.audio.RealtimeParams;
import com.alibaba.dashscope.types.audio.UpdateSessionParams;
import java.io.ByteArrayOutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * One Qwen-Audio realtime spoken turn from a WAV file or the microphone, saved as a 24 kHz WAV
 * reply. Translation of the Python blueprint example
 * 01_atomic_capabilities/audio/realtime_qwen_audio.py.
 *
 * <p>Fixed model {@code qwen-audio-3.0-realtime-plus}, default voice {@code longanqian}; manual
 * end-of-turn (commit + createResponse). Unlike the omni example this dialect uses the legacy flat
 * {@code input_audio_format}/{@code output_audio_format} session fields. WAV input must be mono
 * 16-bit 16 kHz, 0.1–20 s.
 *
 * <pre>
 * mvn -q -f examples/pom.xml exec:java -Dexec.mainClass=com.alibaba.dashscope.examples.atomic.audio.RealtimeQwenAudioDialog -Dexec.args="--wav input.wav --output reply.wav"
 * </pre>
 */
public final class RealtimeQwenAudioDialog {
  private static final String MODEL = "qwen-audio-3.0-realtime-plus";

  public static void main(String[] args) throws Exception {
    Path wav = null;
    Path output = null;
    boolean microphone = false;
    boolean noPlay = false;
    double seconds = 10.0;
    String voice = "longanqian";
    String instructions = "请用简洁自然的中文回答。";
    for (int i = 0; i < args.length; i++) {
      switch (args[i]) {
        case "--wav":
          wav = Paths.get(args[++i]);
          break;
        case "--microphone":
          microphone = true;
          break;
        case "--seconds":
          seconds = Double.parseDouble(args[++i]);
          break;
        case "--voice":
          voice = args[++i];
          break;
        case "--instructions":
          instructions = args[++i];
          break;
        case "--output":
          output = Paths.get(args[++i]);
          break;
        case "--no-play":
          noPlay = true;
          break;
        default:
          System.err.println("unknown argument: " + args[i]);
          usage();
      }
    }
    if (output == null || (wav == null && !microphone) || (wav != null && microphone)) {
      usage();
    }
    if (microphone && (seconds < 0.1 || seconds > 20)) {
      System.err.println("error: --seconds must be between 0.1 and 20");
      System.exit(2);
    }
    AudioCommon.PcmAudio audio = null;
    if (wav != null) {
      audio = AudioCommon.readWav(wav, 16000);
      double duration = audio.pcm.length / 2.0 / 16000;
      if (duration < 0.1 || duration > 20) {
        System.err.println("error: this example accepts single-turn WAV input of 0.1 to 20 seconds");
        System.exit(2);
      }
    }

    ByteArrayOutputStream pcm = new ByteArrayOutputStream();
    int size;
    try (DashScopeClient client = ExampleSupport.client()) {
      RealtimeSession session =
          client.audio().realtime().connect(RealtimeParams.builder().model(MODEL).build());
      ExecutorService pool = Executors.newSingleThreadExecutor();
      try {
        session.connect();
        session.updateSession(
            UpdateSessionParams.builder()
                .modalities(Arrays.asList("text", "audio"))
                .voice(voice)
                .inputAudioFormat("pcm")
                .outputAudioFormat("pcm")
                .enableTurnDetection(false)
                .parameters(Collections.singletonMap("instructions", instructions))
                .build());
        // One receiver thread consumes the single-use event stream (see RealtimeOmniDialog).
        CountDownLatch sessionUpdated = new CountDownLatch(1);
        Future<Integer> receiver =
            pool.submit(
                () -> {
                  try {
                    return RealtimeOmniDialog.receiveReply(session, pcm, sessionUpdated);
                  } finally {
                    sessionUpdated.countDown();
                  }
                });
        if (!sessionUpdated.await(30, TimeUnit.SECONDS)) {
          throw new RuntimeException("No session.updated event received within 30 seconds");
        }
        if (audio != null) {
          RealtimeOmniDialog.sendWav(session, receiver, audio);
        } else {
          RealtimeOmniDialog.sendMicrophone(session, receiver, seconds);
        }
        session.commit();
        session.createResponse();
        size = receiver.get();
      } finally {
        session.close();
        pool.shutdown();
      }
    }
    if (size == 0 || size % 2 != 0) {
      throw new RuntimeException("Response audio is empty or incomplete (" + size + " bytes)");
    }
    AudioCommon.writeWav(output, pcm.toByteArray(), 24000);
    System.out.println(
        "Saved "
            + output.toAbsolutePath()
            + " ("
            + String.format("%.2f", size / 48000.0)
            + " seconds)");
    if (!noPlay) {
      AudioCommon.play(output);
    }
  }

  private static void usage() {
    System.err.println(
        "usage: RealtimeQwenAudioDialog (--wav <in.wav> | --microphone [--seconds 10]) --output"
            + " <reply.wav> [--voice v] [--instructions s] [--no-play]");
    System.exit(2);
  }
}

Connection reuse & voice management

  • client.wsConnection() multiplexes several audio tasks over one WebSocket (AudioConnectionReuse); pass it to asr().recognize(params, connection) / tts().connect(params, connection).
  • audio().voices() manages cloned voices (VoiceCloneManage); vocabularies() / phrases() customize recognition; voiceDesign() designs voices.
  • Behind NAT/proxies, set wsPingInterval (20–30 s) to keep WebSockets alive — see Configuration.

TingWu (meeting transcription)

Job job = client.tingwu().jobs().create(params);   // submit a transcription task
Job done = client.tingwu().jobs().wait(job.getTaskId(), RequestOptions.NONE);

Example: TingWuJobsCreate.

Full runnable example: TingWuJobsCreate.java (auto-synced)
// Copyright (c) Alibaba, Inc. and its affiliates.
package com.alibaba.dashscope.examples.atomic.audio;

import com.alibaba.dashscope.DashScopeClient;
import com.alibaba.dashscope.RequestOptions;
import com.alibaba.dashscope.examples.ExampleSupport;
import com.alibaba.dashscope.resources.jobs.Job;
import com.alibaba.dashscope.types.tingwu.TingWuJobParams;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Offline TingWu job: create a task whose free-form input carries the business-defined fields
 * ({@code fileUrl} — the audio/video file to analyze — and {@code appid} — the TingWu app ID), wait
 * for the terminal state, and print the result URL. Replace the appid default and pass your own
 * publicly accessible file URL before running. Only the offline-jobs part of the Python original is
 * covered here (its realtime websocket session is a separate capability). Usage:
 *
 * <pre>
 * TingWuJobsCreate --url &lt;audio/video file url&gt; [--app-id 123456] [--model tingwu-automotive-service-inspection]
 * </pre>
 *
 * Translation of the Python blueprint example 01_atomic_capabilities/audio/tingwu.py.
 */
public final class TingWuJobsCreate {

  public static void main(String[] args) throws Exception {
    String url = null;
    String appId = "123456"; // Placeholder, as in the Python original; use your own TingWu app ID.
    String model = "tingwu-automotive-service-inspection";
    for (int i = 0; i < args.length; i++) {
      switch (args[i]) {
        case "--url":
          url = value(args, ++i);
          break;
        case "--app-id":
          appId = value(args, ++i);
          break;
        case "--model":
          model = value(args, ++i);
          break;
        default:
          usage();
          System.exit(2);
      }
    }
    if (url == null) {
      usage();
      System.exit(2);
    }

    Map<String, Object> input = new LinkedHashMap<>();
    input.put("fileUrl", url);
    input.put("appid", appId);
    try (DashScopeClient client = ExampleSupport.client()) {
      Job created =
          client
              .tingwu()
              .jobs()
              .create(TingWuJobParams.builder().model(model).input(input).build());
      if (created.isError()) {
        System.err.println("error: " + created.getCode() + " " + created.getMessage());
        System.exit(1);
      }
      System.out.println("task_id: " + created.getTaskId());
      Job job = client.tingwu().jobs().wait(created.getTaskId(), RequestOptions.NONE);
      System.out.println(
          "Task status: " + job.getTaskStatus() + " request_id=" + job.getRequestId());
      if (job.getResultUrl() != null) {
        System.out.println("result_url: " + job.getResultUrl());
      }
      System.out.println(job.getOutput());
      if (!job.isSucceeded()) {
        System.exit(1);
      }
    }
  }

  private static String value(String[] args, int i) {
    if (i >= args.length) {
      usage();
      System.exit(2);
    }
    return args[i];
  }

  private static void usage() {
    System.err.println(
        "usage: TingWuJobsCreate --url <audio/video file url> [--app-id ID] [--model M]");
  }
}