Java SDK

更新时间:
复制 MD 格式

This topic describes how to install and use the Java software development kit (SDK) for Alibaba Cloud Voice Service and provides code examples.

Precautions

Before you use the SDK, familiarize yourself with the API reference. For more information, see API reference.

Installation

You can download the latest version of the SDK from the Maven server or download the nls-common-sdk-demos package.

<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 voice processing client used to process voice tasks. This client is thread-safe. We recommend that you create only one global instance.

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

  • CommonRequestListener: The generic result listener class that listens for detection results. This class is not thread-safe.

    Note

    Notes on using the SDK:

    • NlsClient uses the Netty framework. Creating an NlsClient object consumes time and resources. After an object is created, it can be reused. Therefore, you must align the creation and shutdown of the NlsClient object with your program's lifecycle.

    • CommonRequest objects cannot be reused. Each task requires a new CommonRequest object. For example, to process N audio files in N separate tasks, you must create N CommonRequest objects.

    • CommonRequestListener and CommonRequest objects have a one-to-one correspondence. Do not use the same CommonRequestListener object for different CommonRequest objects. Otherwise, the tasks cannot be distinguished from each other.

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

Code example

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 AudioEventDetectionDemo {

    public static final String TOKEN = "default";      // 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 = "AudioEventDetection";

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

    private static final int SAMPLE_RATE = 16000;

    private static final int CHUNK_DURATION = 200;

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

        InputStream stream = AudioEventDetectionDemo.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", 16000);
        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;
    }
}