Java SDK
Updated at:
This topic describes how to use the Java SDK for Tingwu real-time speech stream ingest. It covers how to install the SDK and provides code samples.
Prerequisites
Before you use the Java SDK for speech stream ingest, read the Development guide.
Download and Install
You can download the Tingwu Real-time Voice Push SDK from the Maven server.
<dependency>
<groupId>com.alibaba.nls</groupId>
<artifactId>nls-sdk-transcriber</artifactId>
<version>2.2.5</version>
</dependency>Sample code
You can download nls-sample-16k.wav. The audio file used in this sample has a sample rate of 16000 Hz.
Note
This sample simulates a single-stream, offline speech recognition session by reading a local file.
For multi-stream online speech recognition, see Step 2 in Real-time meeting speech stream ingest to construct each audio stream frame using the protobuf MultiAudioFrame data structure.
package com.aliyun.sample;
import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.asr.SpeechTranscriber;
import com.alibaba.nls.client.protocol.asr.SpeechTranscriberListener;
import com.alibaba.nls.client.protocol.asr.SpeechTranscriberResponse;
import java.io.File;
import java.io.FileInputStream;
public class SpeechTranscriberSample {
/**
* Create an instance.
* @return
*/
public static NlsClient createClient() {
return new NlsClient("default");
}
/**
* Listen for recognition events and results.
* @return
*/
public static SpeechTranscriberListener getTranscriberListener() {
SpeechTranscriberListener listener = new SpeechTranscriberListener() {
// A transcription result is returned. This message is returned only when RealtimeResultLevel is set to 2.
@Override
public void onTranscriptionResultChange(SpeechTranscriberResponse response) {
System.out.println("task_id: " + response.getTaskId() +
", name: " + response.getName() +
// A status code of "20000000" indicates a successful recognition.
", status: " + response.getStatus() +
// The sentence number, which starts from 1 and increments.
", index: " + response.getTransSentenceIndex() +
// The current recognition result.
", result: " + response.getTransSentenceText() +
// The current word-level recognition result.
", words: " + response.getWords() +
// The duration of the processed audio in milliseconds.
", time: " + response.getTransSentenceTime());
}
@Override
public void onTranscriberStart(SpeechTranscriberResponse response) {
// The task_id is the unique identifier for communication between the client and the server. Provide this task_id when you report an issue.
System.out.println("task_id: " + response.getTaskId() + ", name: " + response.getName() + ", status: " + response.getStatus());
}
@Override
public void onSentenceBegin(SpeechTranscriberResponse response) {
System.out.println("task_id: " + response.getTaskId() + ", name: " + response.getName() + ", status: " + response.getStatus());
}
// A sentence is recognized. The server automatically splits sentences. This message is returned when the end of a sentence is detected.
@Override
public void onSentenceEnd(SpeechTranscriberResponse response) {
System.out.println("task_id: " + response.getTaskId() +
", name: " + response.getName() +
// A status code of "20000000" indicates a successful recognition.
", status: " + response.getStatus() +
// The sentence number, which starts from 1 and increments.
", index: " + response.getTransSentenceIndex() +
// The current recognition result.
", result: " + response.getTransSentenceText() +
// The current word-level recognition result.
", words: " + response.getWords() +
// The start time.
", begin_time: " + response.getSentenceBeginTime() +
// The duration of the processed audio in milliseconds.
", time: " + response.getTransSentenceTime());
}
// The recognition is complete.
@Override
public void onTranscriptionComplete(SpeechTranscriberResponse response) {
System.out.println("task_id: " + response.getTaskId() + ", name: " + response.getName() + ", status: " + response.getStatus());
}
@Override
public void onFail(SpeechTranscriberResponse response) {
// The task_id is the unique identifier for communication between the client and the server. Provide this task_id when you report an issue.
System.out.println("task_id: " + response.getTaskId() + ", status: " + response.getStatus() + ", status_text: " + response.getStatusText());
}
};
return listener;
}
/**
* Calculate the equivalent audio duration from the size of the binary data.
* sampleRate: 16000.
* @param dataSize
* @return
*/
public static int getSleepDelta(int dataSize) {
return dataSize / (2 * 16000 / 1000);
}
/**
* Establish a persistent WebSocket connection with the server.
* @param nlsClient
* @param meetingJoinUrl
* @return
*/
public static SpeechTranscriber startTranscriber(NlsClient nlsClient, String meetingJoinUrl) {
SpeechTranscriber transcriber = null;
try {
transcriber = new SpeechTranscriber(nlsClient, "default", getTranscriberListener(), meetingJoinUrl);
// If you pause and then resume recognition, and AudioOutputEnabled was set to false or not set when the meeting was created, you must set the time offset in milliseconds to resume recognition.
// transcriber.addCustomedParam("tw_time_offset", xxx);
// Modify the translation configuration before you start recognition.
// addTranslateConfigOnStart(speechTranscriber, true, "en");
// Send the start recognition instruction to the server and wait for confirmation.
transcriber.start();
} catch (Exception e) {
// If needed, print the error.
}
return transcriber;
}
public static void process(SpeechTranscriber transcriber, byte[] data, int length) {
transcriber.send(data, length);
}
public static void stopTranscriber(SpeechTranscriber transcriber) {
if (transcriber != null) {
try {
transcriber.stop();
} catch (Exception error) {
// If needed, print the error.
} finally {
transcriber.close();
}
}
}
public static void main(String[] args) throws Exception {
// This sample uses a local file to simulate sending real-time stream data. In a real-world application, you can collect or receive an audio stream in real time and send it to the server.
String filepath = "nls-sample-16k.wav";
String meetingJoinUrl = "The audio ingest URL for the meeting, returned from the CreateMeeting API call";
NlsClient nlsClient = createClient();
SpeechTranscriber transcriber = SpeechTranscriberSample.startTranscriber(nlsClient, meetingJoinUrl);
File file = new File(filepath);
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[3200];
int length;
while ((length = fis.read(data)) > 0) {
System.out.println("send data pack length: " + length);
SpeechTranscriberSample.process(transcriber, data, length);
// This sample reads a local file to simulate getting and sending a real-time audio stream. A sleep is required because the file is read quickly.
// A sleep is not required if you get the audio in real time.
int deltaSleep = getSleepDelta(length);
Thread.sleep(deltaSleep);
// During recognition, modify the translation configuration as needed. Do not call this in a loop. This is only an example to show that the call can be made during audio stream ingest.
// sendTranslateConfigUpdateDirective(speechTranscriber, true, "en");
}
// Notify the server that the audio data is sent and wait for the server to finish processing.
long now = System.currentTimeMillis();
System.out.println("ASR wait for complete");
SpeechTranscriberSample.stopTranscriber(transcriber);
System.out.println("ASR latency : " + (System.currentTimeMillis() - now) + " ms");
}
// The descriptions of the translateResultEnabled and translateLanguages parameters are the same as the descriptions of the parameters with the same names in the CreateMeetingTrans API.
public void addTranslateConfigOnStart(SpeechTranscriber speechTranscriber, boolean translateResultEnabled, String translateLanguages) {
if (translateResultEnabled) {
speechTranscriber.addCustomedParam("translate_result_enabled", true);
speechTranscriber.addCustomedParam("translate_languages", translateLanguages);
} else {
speechTranscriber.addCustomedParam("translate_result_enabled", false);
}
}
// The descriptions of the translateResultEnabled and translateLanguages parameters are the same as the descriptions of the parameters with the same names in the CreateMeetingTrans API.
public void sendTranslateConfigUpdateDirective(SpeechTranscriber speechTranscriber, boolean translateResultEnabled, String translateLanguages) {
Map<String, Object> directive = new HashMap<>();
Map<String, Object> header = new HashMap<>();
header.put("name", "UpdateConfig");
directive.put("header", header);
Map<String, Object> payload = new HashMap<>();
payload.put("instruction_id", UUID.randomUUID().toString()); // After you set this parameter and send the instruction, an UpdateConfigACK message is returned. For the message definition, see the "Development Reference" section in the documentation.
if (translateResultEnabled) {
payload.put("translate_result_enabled", true);
payload.put("translate_languages", translateLanguages);
} else {
payload.put("translate_result_enabled", false);
}
directive.put("payload", payload);
String directiveJsonString = JSON.toJSONString(directive); // Call a JSON library to convert the Map to a JSON string.
speechTranscriber.getConnection().sendText(directiveJsonString);
}
}Is this page helpful?