語音合成時間戳記標記漢字或英文單詞在合成音頻中的起止時間,可用於視頻字幕同步、文字高亮和虛擬人口型同步。通過請求參數開啟該功能後,在接收音頻流的同時擷取時間戳記。
使用限制
-
只有支援字層級音素邊界介面的發音人才支援字級時間戳記。
-
短文本語音合成 RESTful API 不返回時間戳記資訊。擷取時間戳記需使用 WebSocket 介面或相應 SDK。
-
字幕文本按發音產生,不一定與原文逐字對應。例如,
12可以對應“十”和“二”兩個字幕單元。顯示字幕時使用原始文本,並根據返回時間確定句首、句尾或高亮位置,不要直接將字幕索引作為原始字串的字元位移。
程式碼範例
以下 Java 樣本使用 nls-sdk-tts 2.1.6,從環境變數讀取專案 AppKey 和有效 NLS Token,輸出字幕資訊,並將音頻儲存為 tts_test.wav。檔案已存在時會被覆蓋。
添加依賴和配置憑證
在 Maven 專案的 dependencies 中添加以下依賴:
<dependency>
<groupId>com.alibaba.nls</groupId>
<artifactId>nls-sdk-tts</artifactId>
<version>2.1.6</version>
</dependency>
在運行環境中設定 NLS_APP_KEY 和 NLS_TOKEN,分別填寫專案 AppKey 和 NLS Token。Token 必須有效且與專案所屬帳號匹配,不使用 STS Token 或其他產品的 API Key 代替。
合成並接收時間戳記
import com.alibaba.fastjson.JSONArray;
import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.OutputFormatEnum;
import com.alibaba.nls.client.protocol.SampleRateEnum;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizer;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerListener;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public class SpeechSynthesizerDemo {
private static String requiredEnv(String name) {
String value = System.getenv(name);
if (value == null || value.trim().isEmpty()) {
throw new IllegalArgumentException("Missing environment variable: " + name);
}
return value;
}
public static void main(String[] args) throws Exception {
String appKey = requiredEnv("NLS_APP_KEY");
String token = requiredEnv("NLS_TOKEN");
String endpoint = "wss://nls-gateway-ap-southeast-1.aliyuncs.com/ws/v1";
NlsClient client = new NlsClient(endpoint, token);
try (OutputStream audio = Files.newOutputStream(Paths.get("tts_test.wav"))) {
AtomicReference<String> failure = new AtomicReference<>();
AtomicBoolean completed = new AtomicBoolean(false);
AtomicBoolean firstAudio = new AtomicBoolean(true);
final long start = System.nanoTime();
SpeechSynthesizerListener listener = new SpeechSynthesizerListener() {
@Override
public void onMessage(ByteBuffer message) {
if (firstAudio.compareAndSet(true, false)) {
System.out.println("First audio latency (ms): "
+ (System.nanoTime() - start) / 1_000_000);
}
byte[] bytes = new byte[message.remaining()];
message.get(bytes);
try {
audio.write(bytes);
} catch (IOException e) {
failure.compareAndSet(null, "Failed to write audio: " + e.getMessage());
}
}
@Override
public void onMetaInfo(SpeechSynthesizerResponse response) {
JSONArray subtitles = (JSONArray) response.getObject("subtitles");
if (subtitles != null) {
System.out.println("MetaInfo: " + subtitles.toJSONString());
}
}
@Override
public void onComplete(SpeechSynthesizerResponse response) {
completed.set(true);
System.out.println("SynthesisCompleted: " + response.getTaskId());
}
@Override
public void onFail(SpeechSynthesizerResponse response) {
failure.set("task_id=" + response.getTaskId()
+ ", status=" + response.getStatus()
+ ", status_text=" + response.getStatusText());
}
};
SpeechSynthesizer synthesizer = new SpeechSynthesizer(client, listener);
try {
synthesizer.setAppKey(appKey);
synthesizer.setFormat(OutputFormatEnum.WAV);
synthesizer.setSampleRate(SampleRateEnum.SAMPLE_RATE_16K);
synthesizer.setVoice("siyue");
synthesizer.setPitchRate(100);
synthesizer.setSpeechRate(100);
synthesizer.setText("Hello world. I have 12 apples.");
synthesizer.addCustomedParam("enable_subtitle", true);
synthesizer.start();
synthesizer.waitForComplete();
if (failure.get() != null) {
throw new IllegalStateException(failure.get());
}
if (!completed.get()) {
throw new IllegalStateException("Synthesis did not complete");
}
System.out.println("Audio saved to tts_test.wav");
} finally {
synthesizer.close();
}
} finally {
client.shutdown();
}
}
}
合成成功後,程式輸出 MetaInfo 字幕數組、SynthesisCompleted 及音頻檔案儲存提示。首包延遲從發起合成前開始計時,到收到第一包音頻結束;它不同於接收完整音頻所需的時間。
樣本將音頻儲存為檔案。對即時性要求較高時,可在 onMessage 收到音頻後邊接收邊播放,無需等到全部合成完成。
字級時間戳記
參數設定
發起合成請求前,將 enable_subtitle 設定為 true。該功能預設關閉。Java SDK 設定方式如下:
synthesizer.addCustomedParam("enable_subtitle", true);
服務端響應
服務端通過 MetaInfo 事件返回時間戳記,payload.subtitles 為字幕數組。Java SDK 通過 onMetaInfo 回調接收該事件。
subtitles 元素欄位
|
欄位 |
類型 |
說明 |
|
text |
String |
按發音產生的文本單元,如一個漢字或英文單詞。 |
|
begin_time |
Integer |
該文本單元在合成音頻中的開始時間,單位為毫秒。 |
|
end_time |
Integer |
該文本單元在合成音頻中的結束時間,單位為毫秒。 |
|
phoneme |
String |
僅開啟字級時間戳記時,返回字串 |
|
begin_index |
Integer |
文本單元的起始索引,從 0 開始,不是原始字串的字元位移。 |
|
end_index |
Integer |
文本單元的結束索引,不包含該位置。 |
例如,Hello world! 的兩個單詞分別對應索引區間 [0, 1) 和 [1, 2);標點可能佔用索引位置,你好,世界。 中“世”的起始索引為 3。
一次合成可能返回多個 MetaInfo 事件,其中的字幕可能重複或包含此前返回的內容。處理字幕時,根據索引和時間更新已有字幕資料,不要直接追加每次返回的整個數組。
返回樣本
以下為合成 Hello world! 時返回的 payload 樣本,時間值隨音色、語速和文本變化。
{
"subtitles": [
{
"text": "Hello",
"phoneme": "null",
"begin_index": 0,
"end_index": 1,
"begin_time": 0,
"end_time": 328
},
{
"text": "world",
"phoneme": "null",
"begin_index": 1,
"end_index": 2,
"begin_time": 328,
"end_time": 775
}
]
}