语音(TTS / ASR / 实时)¶
client.audio() 聚合语音资源:tts()(合成)、asr()(识别)、realtime()(WebSocket 语音
对话),以及 voices()、vocabularies()、phrases() 与 voiceDesign()。听悟会议转写在
client.tingwu()。以下代码均改编自可运行的
audio 示例。
开发中
client.audio() 语音模块仍在开发中,接口可能在后续版本中发生变化(与
com.alibaba.dashscope.audio 包的 Javadoc 说明一致;client.tingwu() 不在此列)。
升级 SDK 时请留意本页涉及的 API 变更。
语音合成¶
一次性 HTTP 合成返回完整音频字节(format("pcm") 时为原始 PCM);长文本建议用流式变体:
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("你好,DashScope")
.format("pcm") // 原始 PCM;如需 WAV 请自行封装
.sampleRate(24000)
.build());
tts().stream(params)→ResponseStream<byte[]>—— HTTP 增量音频。tts().connect(TtsConnectParams)→SynthesisSession—— WebSocket 合成,支持增量文本输入。
示例:TtsHttpSynthesize、TtsHttpStreamSynthesize、TtsWebsocketConnect。
完整可运行示例:TtsHttpSynthesize.java(自动同步)
// 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 <text> <output.wav> [--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]");
}
}
语音识别¶
实时识别打开一个 RecognitionSession:一个线程按节奏发送音频帧,另一个线程遍历 results():
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();
// 接收线程:for (AsrResult r : session.results()) { r.getSentence().getText(); ... }
for (byte[] frame : pcmChunks) { // 每帧约 100 ms 音频,按节奏发送
session.sendAudioFrame(frame);
}
session.stop();
} finally {
session.close();
}
AsrResult.Sentence.getSentenceEnd() 区分最终句与中间结果;session.getRequestId() 与
getFirstPackageDelay() 用于诊断(未识别到任何内容时 delay 保持 null)。
文件转写用 asr().transcribe(AsrTranscribeParams) 提交异步 Job(asr().jobs() 等待/查询)。
示例:AsrWebsocketRecognize、AsrHttpStreamRecognize、AsrMicrophoneRecognize、
AsrJobsTranscribe。
完整可运行示例:AsrWebsocketRecognize.java(自动同步)
// 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().connect(RealtimeParams) 打开 RealtimeSession(WebSocket)。配置会话、追加音频,
然后 commit 并请求响应;由单个接收线程消费 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) // 手动结束回合:commit + createResponse
.build());
// 接收线程遍历 session.events()(单次消费流)
session.appendAudio(pcmFrame);
session.commit();
session.createResponse();
} finally {
session.close();
}
示例:RealtimeQwenAudioDialog(Qwen-Audio 方言)、RealtimeOmniDialog(omni)、
RealtimeTranslation(实时翻译)。
完整可运行示例:RealtimeQwenAudioDialog.java(自动同步)
// 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);
}
}
连接复用与声音管理¶
client.wsConnection()在一条 WebSocket 上复用多个音频任务(AudioConnectionReuse); 传入asr().recognize(params, connection)/tts().connect(params, connection)。audio().voices()管理克隆音色(VoiceCloneManage);vocabularies()/phrases()定制 识别;voiceDesign()设计音色。- NAT/代理后建议设置
wsPingInterval(20–30 s)保持 WebSocket 存活 —— 见配置。
听悟(会议转写)¶
Job job = client.tingwu().jobs().create(params); // 提交转写任务
Job done = client.tingwu().jobs().wait(job.getTaskId(), RequestOptions.NONE);
示例:TingWuJobsCreate。
完整可运行示例:TingWuJobsCreate.java(自动同步)
// 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 <audio/video file url> [--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]");
}
}