Java SDK

更新时间:
复制 MD 格式

This topic describes how to use the Java software development kit (SDK) provided by Alibaba Cloud Voice Service. It includes installation instructions and code examples.

Precautions

Before you use the SDK, read the API reference. For more information, see API reference.

Download and install

You can download the latest version of the SDK, nls-common-sdk-demos, from the Maven repository.

<dependency>
  <groupId>com.alibaba.nls</groupId>
  <artifactId>nls-sdk-common</artifactId>
  <version>2.2.1</version>
</dependency>
<dependency>
  <groupId>com.alibaba.nls</groupId>
  <artifactId>nls-sdk-request</artifactId>
  <version>2.2.1</version>
</dependency>

Key interfaces

  • NlsClient: The client for voice processing. This client is used to process voice tasks. This client is thread-safe. You should create only one global instance.

  • CommonRequest: A generic request class. It is used to set request parameters and send requests and audio data. This class is not thread-safe.

  • CommonRequestListener: A generic listener class for results. It is used to listen for identification results. This class is not thread-safe.

    Note

    Notes on SDK calls:

    • NlsClient uses the Netty framework. Creating an NlsClient object consumes significant time and resources. After an object is created, it can be reused. You should align the creation and shutdown of the NlsClient object with the lifecycle of your program.

    • CommonRequest objects cannot be reused. You must create a unique CommonRequest object for each task. For example, to process N audio files in N tasks, you must create N CommonRequest objects.

    • Each CommonRequestListener object corresponds to a single CommonRequest object. Do not use the same CommonRequestListener object for multiple CommonRequest objects. If you do, the tasks cannot be distinguished from each other.

    • The Java SDK depends on the Netty network library. If your application also uses Netty, you must update its version to 4.1.17.Final or later.

Sample code

package com.alibaba.nls.demo;

import com.alibaba.nls.client.protocol.NlsClient;
import com.alibaba.nls.client.protocol.commonrequest.CommonRequest;
import com.alibaba.nls.client.protocol.commonrequest.CommonRequestListener;
import com.alibaba.nls.client.protocol.commonrequest.CommonRequestResponse;

import java.io.InputStream;
import java.util.Arrays;

public class GenderIdentificationDemo {

    public static final String TOKEN = "default";      // For information about how to obtain a token, see https://help.aliyun.com/document_detail/450514.html

    public static final String APPKEY = "default";      // To obtain an AppKey, go to the console: https://nls-portal.console.aliyun.com/applist

    private static final String NAMESPACE = "GenderIdentification";

    private static final String URL = "wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1";

    private static final int SAMPLE_RATE = 8000;

    private static final int CHUNK_DURATION = 2000;

    public static void main(String[] args) throws Exception {
        NlsClient client = new NlsClient(URL, TOKEN);

        InputStream stream = GenderIdentificationDemo.class.getResourceAsStream("/test.pcm");

        CommonRequestListener listener = getListener();
        CommonRequest request = new CommonRequest(client, listener, NAMESPACE);
        request.setAppKey(APPKEY);
        request.addCustomedParam("format", "pcm");
        request.addCustomedParam("sample_rate", 8000);
        request.start();
        int chunkSize = SAMPLE_RATE * 2 / 1000 * CHUNK_DURATION;
        byte[] data = new byte[chunkSize];
        while (true) {
            int len = stream.read(data);
            if (len < 0) {
                break;
            }
            if (len > 0) {
                request.send(Arrays.copyOf(data, len));
            }
            Thread.sleep(CHUNK_DURATION / 10);
        }
        request.stop();

        client.shutdown();
    }

    private static CommonRequestListener getListener() {
        CommonRequestListener listener = new CommonRequestListener() {
            @Override
            public void onStarted(CommonRequestResponse response) {
                System.out.println(
                    "onStarted, taskId: " + response.getTaskId() + ", header: " + response.header + ", payload: "
                        + response.payload);
            }

            @Override
            public void onEvent(CommonRequestResponse response) {
                System.out.println(
                    "onEvent, taskId: " + response.getTaskId() + ", header: " + response.header + ", payload: "
                        + response.payload);
            }

            @Override
            public void onStopped(CommonRequestResponse response) {
                System.out.println(
                    "onStopped, taskId: " + response.getTaskId() + ", header: " + response.header + ", payload: "
                        + response.payload);
            }

            @Override
            public void onFailed(CommonRequestResponse response) {
                System.out.println(
                    "onFailed, taskId: " + response.getTaskId() + ", header: " + response.header + ", payload: "
                        + response.payload);
            }
        };
        return listener;
    }
}