All Products
Search
Document Center

:SDK for Java

Last Updated:Nov 08, 2022

The recording file recognition service provides an SDK for Java. This topic describes how to install the SDK for Java and provides sample code for you to use the SDK.

Prerequisites

  • You understand how the SDK works. For more information, see Overview.

  • Intelligent Speech Interaction 2.0 is activated. For more information, see Activate Intelligent Speech Interaction. The SDK in this topic applies only to Intelligent Speech Interaction 2.0. If you use Intelligent Speech Interaction 1.0, you must update Intelligent Speech Interaction to version 2.0.

SDK description

In the Java demo of the recording file recognition service, the CommonRequest method of Alibaba Cloud SDK for Java is used to send Alibaba Cloud pctowap open platform (POP) API requests in a remote procedure call (RPC) style. You can send a recording file recognition request and query the recording file recognition result. For more information, see Use CommonRequest.

Important

Alibaba Cloud SDK for Java does not support code development in Android.

Add Java dependencies

You only need to add dependencies on the core library of Alibaba Cloud SDK for Java and the Alibaba open source library Fastjson. The core library version of Alibaba Cloud SDK for Java must be V3.5.0 or later. If the version is V4.0.0 or later, you must add dependencies on third-party libraries as prompted.

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>3.7.1</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.83</version>
</dependency>

SDK description

Note

Download the nls-sample-16k.wav file. The recording file in the demo is a pulse-code modulation (PCM) encoded file with an audio sampling rate of 16,000 Hz. The demo uses a universal model.

Authentication

Use the AccessKey ID and AccessKey secret of your Alibaba Cloud account to call Alibaba Cloud SDK for Java and create a client. For more information about how to obtain the AccessKey ID and AccessKey secret, see Activate Intelligent Speech Interaction. You can use the following sample code:

final String accessKeyId = "Your AccessKey ID";
final String accessKeySecret = "Your AccessKey secret";
/**
 * The region ID.
 */
final String regionId = "ap-southeast-1";
final String endpointName = "ap-southeast-1";
final String product = "nls-filetrans";
final String domain = "filetrans.ap-southeast-1.aliyuncs.com";

IAcsClient client;
// Set the endpoint of the service.
DefaultProfile.addEndpoint(endpointName, regionId, product, domain);
// Create and initialize a DefaultAcsClient instance.
DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
client = new DefaultAcsClient(profile);

Recording file recognition request

The Java demo uses the polling method. You can send a recording file recognition request and obtain the task ID for subsequent recognition result polling.

Note

For more information about how to set request parameters, see Overview. Set only the parameters in the JSON string and use the default values of parameters for other methods.

/**
 * Create a CommonRequest object and set request parameters.
 */
CommonRequest postRequest = new CommonRequest();
postRequest.setDomain("filetrans.ap-southeast-1.aliyuncs.com"); // Set the domain name. Do not modify its value.
postRequest.setVersion("2019-08-23");         // Set the version of the API. Do not modify its value.
postRequest.setAction("SubmitTask");          // Set the action that you want to perform. Do not modify its value.
postRequest.setProduct("nls-filetrans");      // Set the name of the service. Do not modify its value.
// Set request parameters in JSON format to the body of the recording file recognition request.
JSONObject taskObject = new JSONObject();
taskObject.put("appkey", "Your appkey");    // Set the appkey of your project.
taskObject.put("file_link", "Your recording file URL");  // Set the URL of the recording file that you want to recognize.
taskObject.put(KEY_VERSION, "4.0");  // Specify the version of the recording file recognition service. If you are a new user, set this parameter to 4.0. If you use the default version 2.0, comment out this parameter.
String task = taskObject.toJSONString();
postRequest.putBodyParameter("Task", task);  // Set the request body, including the request parameters in JSON format.
postRequest.setMethod(MethodType.POST);      // Use the POST method to send the request.
/**
 * Send the recording file recognition request.
 */
String taskId = "";   // Obtain the ID of the recording file recognition task. You can use the task ID to poll the recognition result.
CommonResponse postResponse = client.getCommonResponse(postRequest);
if (postResponse.getHttpStatus() == 200) {
    JSONObject result = JSONObject.parseObject(postResponse.getData());
    String statusText = result.getString("StatusText");
    if ("SUCCESS".equals(statusText)) {
        System.out.println("Success response to the recording file recognition request: " + result.toJSONString());
        taskId = result.getString("TaskId");
    }
    else {
        System.out.println("Error response to the recording file recognition request: " + result.toJSONString());
        return;
    }
}
else {
    System.err.println("The recording file recognition request fails. HTTP status code: " + postResponse.getHttpStatus());
    System.err.println("Error response to the recording file recognition request: " + JSONObject.toJSONString(postResponse));
    return;
}

Query request for the recording file recognition result

You can use the obtained task ID to query the recording file recognition result.

/**
 * Create a CommonRequest object and specify the task ID.
 */
CommonRequest getRequest = new CommonRequest();
getRequest.setDomain("filetrans.ap-southeast-1.aliyuncs.com");   // Set the domain name. Do not modify its value.
getRequest.setVersion("2019-08-23");             // Set the version of the API. Do not modify its value.
getRequest.setAction("GetTaskResult");           // Set the action that you want to perform. Do not modify its value.
getRequest.setProduct("nls-filetrans");          // Set the name of the service. Do not modify its value.
getRequest.putQueryParameter("TaskId", taskId);  // Specify the ID of the recognition task.
getRequest.setMethod(MethodType.GET);            // Use the GET method to send the request.
/**
 * Send the query request for the recording file recognition result.
 * Poll the recognition result until the status message that the server returns is SUCCESS, SUCCESS_WITH_NO_VALID_FRAGMENT, or an error message.
 */
String statusText = "";
while (true) {
    CommonResponse getResponse = client.getCommonResponse(getRequest);
    if (getResponse.getHttpStatus() ! = 200) {
        System.err.println("Failed to query the recording file recognition result. HTTP status code: " + getResponse.getHttpStatus());
        System.err.println("Error response to the query request for the recording file recognition result: " + getResponse.getData());
        break;
    }
    JSONObject result = JSONObject.parseObject(getResponse.getData());
    System.out.println("Queried recording file recognition result: " + result.toJSONString());
    statusText = result.getString("StatusText");
    if ("RUNNING".equals(statusText) || "QUEUEING".equals(statusText)) {
        // Continue the polling.
        Thread.sleep(3000);
    }
    else {
        break;
    }
}
if ("SUCCESS".equals(statusText) || "SUCCESS_WITH_NO_VALID_FRAGMENT".equals(statusText)) {
    System.out.println("The recording file is recognized.") ;
}
else {
    System.err.println("Failed to recognize the recording file.") ;
}

Sample code

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
public class FileTransJavaDemo {
    // The constant parameters, such as the region ID. Do not modify their values.
    public static final String REGIONID = "ap-southeast-1";
    public static final String ENDPOINTNAME = "ap-southeast-1";
    public static final String PRODUCT = "nls-filetrans";
    public static final String DOMAIN = "filetrans.ap-southeast-1.aliyuncs.com";
    public static final String API_VERSION = "2019-08-23";
    public static final String POST_REQUEST_ACTION = "SubmitTask";
    public static final String GET_REQUEST_ACTION = "GetTaskResult";
    // The request parameters.
    public static final String KEY_APP_KEY = "appkey";
    public static final String KEY_FILE_LINK = "file_link";
    public static final String KEY_VERSION = "version";
    public static final String KEY_ENABLE_WORDS = "enable_words";
    // The response parameters.
    public static final String KEY_TASK = "Task";
    public static final String KEY_TASK_ID = "TaskId";
    public static final String KEY_STATUS_TEXT = "StatusText";
    public static final String KEY_RESULT = "Result";
    // The status values.
    public static final String STATUS_SUCCESS = "SUCCESS";
    private static final String STATUS_RUNNING = "RUNNING";
    private static final String STATUS_QUEUEING = "QUEUEING";
    // Create and authenticate a client.
    IAcsClient client;
    public FileTransJavaDemo(String accessKeyId, String accessKeySecret) {
        // Set the endpoint of the service.
        try {
            DefaultProfile.addEndpoint(ENDPOINTNAME, REGIONID, PRODUCT, DOMAIN);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        // Create and initialize a DefaultAcsClient instance.
        DefaultProfile profile = DefaultProfile.getProfile(REGIONID, accessKeyId, accessKeySecret);
        this.client = new DefaultAcsClient(profile);
    }
    public String submitFileTransRequest(String appKey, String fileLink) {
        /**
         * 1. Create a CommonRequest object and set request parameters.
         */
        CommonRequest postRequest = new CommonRequest();
        // Set the domain name.
        postRequest.setDomain(DOMAIN);
        // Set the version of the API, in YYYY-MM-DD format.
        postRequest.setVersion(API_VERSION);
        // Set the action that you want to perform.
        postRequest.setAction(POST_REQUEST_ACTION);
        // Set the name of the service.
        postRequest.setProduct(PRODUCT);
        /**
         * 2. Set request parameters in JSON format to the body of the recording file recognition request.
         */
        JSONObject taskObject = new JSONObject();
        // Set the appkey of your project.
        taskObject.put(KEY_APP_KEY, appKey);
        // Set the URL of the recording file that you want to recognize.
        taskObject.put(KEY_FILE_LINK, fileLink);
        // Specify the version of the recording file recognition service. If you are a new user, set this parameter to 4.0. If you use the default version 2.0, comment out this parameter.
        taskObject.put(KEY_VERSION, "4.0");
        // Specify whether to return the recognition results of words. Default value: false. This parameter takes effect only when the version of the recording file recognition service is 4.0 or later.
        taskObject.put(KEY_ENABLE_WORDS, true);
        String task = taskObject.toJSONString();
        System.out.println(task);
        // Set the request body, including the request parameters in JSON format.
        postRequest.putBodyParameter(KEY_TASK, task);
        // Use the POST method to send the request.
        postRequest.setMethod(MethodType.POST);
        /**
         * 3. Send the recording file recognition request. Obtain the ID of the recording file recognition task. You can use the task ID to poll the recognition result.
         */
        String taskId = null;
        try {
            CommonResponse postResponse = client.getCommonResponse(postRequest);
            System.err.println("Response to the recording file recognition request: " + postResponse.getData());
            if (postResponse.getHttpStatus() == 200) {
                JSONObject result = JSONObject.parseObject(postResponse.getData());
                String statusText = result.getString(KEY_STATUS_TEXT);
                if (STATUS_SUCCESS.equals(statusText)) {
                    taskId = result.getString(KEY_TASK_ID);
                }
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return taskId;
    }
    public String getFileTransResult(String taskId) {
        /**
         * 1. Create a CommonRequest object and specify the task ID.
         */
        CommonRequest getRequest = new CommonRequest();
        // Set the domain name.
        getRequest.setDomain(DOMAIN);
        // Set the version of the API.
        getRequest.setVersion(API_VERSION);
        // Set the action that you want to perform.
        getRequest.setAction(GET_REQUEST_ACTION);
        // Set the name of the service.
        getRequest.setProduct(PRODUCT);
        // Set the ID of the recognition task.
        getRequest.putQueryParameter(KEY_TASK_ID, taskId);
        // Use the GET method to send the request.
        getRequest.setMethod(MethodType.GET);
        /**
         * 2. Send the query request for the recording file recognition result.
         * Poll the recognition result until the status message that the server returns is SUCCESS or an error message.
         */
        String result = null;
        while (true) {
            try {
                CommonResponse getResponse = client.getCommonResponse(getRequest);
                System.err.println("Queried recording file recognition result: " + getResponse.getData());
                if (getResponse.getHttpStatus() ! = 200) {
                    break;
                }
                JSONObject rootObj = JSONObject.parseObject(getResponse.getData());
                String statusText = rootObj.getString(KEY_STATUS_TEXT);
                if (STATUS_RUNNING.equals(statusText) || STATUS_QUEUEING.equals(statusText)) {
                    // Continue the polling. You must set an appropriate polling interval.
                    Thread.sleep(10000);
                }
                else {
                    // If the status message is SUCCESS, the recognition result is returned. If the status message is an error message, NULL is returned.
                    if (STATUS_SUCCESS.equals(statusText)) {
                        result = rootObj.getString(KEY_RESULT);
                       // If the status message is SUCCESS but no recognition result is returned, the file may contain only silence or noise.
                        if(result == null) {
                            result = "";
                        }
                    }
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    public static void main(String args[]) throws Exception {
        if (args.length < 3) {
            System.err.println("FileTransJavaDemo need params: <AccessKey Id> <AccessKey Secret> <app-key>");
        }
        final String accessKeyId = args[0];
        final String accessKeySecret = args[1];
        final String appKey = args[2];
        String fileLink = "https://aliyun-nls.oss-cn-hangzhou.aliyuncs.com/asr/fileASR/examples/nls-sample-16k.wav";
        FileTransJavaDemo demo = new FileTransJavaDemo(accessKeyId, accessKeySecret);
        // Step 1: Send the recording file recognition request and obtain the task ID for subsequent recognition result polling.
        String taskId = demo.submitFileTransRequest(appKey, fileLink);
        if (taskId ! = null) {
            System.out.println("The recording file recognition request is successful. task_id: " + taskId);
        }
        else {
            System.out.println("The recording file recognition request fails.") ;
            return;
        }
        // Step 2: Poll the recognition result based on the task ID.
        String result = demo.getFileTransResult(taskId);
        if (result ! = null) {
            System.out.println("Queried recording file recognition result: " + result);
        }
        else {
            System.out.println("Failed to query the recording file recognition result.") ;
        }
    }
}
Note

If you use the callback method, you must set the enable_callback and callback_url parameters.

taskObject.put("enable_callback", true);
taskObject.put("callback_url", "Callback URL");

Callback method: You can also use the callback method to query the recording file recognition result. Assume that the callback URL is http://ip:port/filetrans/callback/result.

package com.example.filetrans;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@RequestMapping("/filetrans/callback")
@RestController
public class FiletransCallBack {
    // Status codes that start with 4 indicate client errors.
    private static final Pattern PATTERN_CLIENT_ERR = Pattern.compile("4105[0-9]*");
    // Status codes that start with 5 indicate server errors.
    private static final Pattern PATTERN_SERVER_ERR = Pattern.compile("5105[0-9]*");
    // You must use the POST method.
    @RequestMapping(value = "result", method = RequestMethod.POST)
    public void GetResult(HttpServletRequest request) {
        byte [] buffer = new byte[request.getContentLength()];
        ServletInputStream in = null;
        try {
            in = request.getInputStream();
            in.read(buffer, 0 ,request.getContentLength());
            in.close();
            // Obtain the recording file recognition result in JSON format.
            String result = new String(buffer);
            JSONObject jsonResult = JSONObject.parseObject(result);
            // Parse and return the recognition result.
            System.out.println("Queried recording file recognition result: " + result);
            System.out.println("TaskId: " + jsonResult.getString("TaskId"));
            System.out.println("StatusCode: " + jsonResult.getString("StatusCode"));
            System.out.println("StatusText: " + jsonResult.getString("StatusText"));
            Matcher matcherClient = PATTERN_CLIENT_ERR.matcher(jsonResult.getString("StatusCode"));
            Matcher matcherServer = PATTERN_SERVER_ERR.matcher(jsonResult.getString("StatusCode"));
            // Status codes that start with 2 indicate the normal status. If you use the callback method, the server returns only 21050000 to indicate the normal status.
            if("21050000".equals(jsonResult.getString("StatusCode"))) {
                System.out.println("RequestTime: " + jsonResult.getString("RequestTime"));
                System.out.println("SolveTime: " + jsonResult.getString("SolveTime"));
                System.out.println("BizDuration: " + jsonResult.getString("BizDuration"));
                System.out.println("Result.Sentences.size: " +
                    jsonResult.getJSONObject("Result").getJSONArray("Sentences").size());
                for (int i = 0; i < jsonResult.getJSONObject("Result").getJSONArray("Sentences").size(); i++) {
                    System.out.println("Result.Sentences[" + i + "].BeginTime: " +
                        jsonResult.getJSONObject("Result").getJSONArray("Sentences").getJSONObject(i).getString("BeginTime"));
                    System.out.println("Result.Sentences[" + i + "].EndTime: " +
                        jsonResult.getJSONObject("Result").getJSONArray("Sentences").getJSONObject(i).getString("EndTime"));
                    System.out.println("Result.Sentences[" + i + "].SilenceDuration: " +
                        jsonResult.getJSONObject("Result").getJSONArray("Sentences").getJSONObject(i).getString("SilenceDuration"));
                    System.out.println("Result.Sentences[" + i + "].Text: " +
                        jsonResult.getJSONObject("Result").getJSONArray("Sentences").getJSONObject(i).getString("Text"));
                    System.out.println("Result.Sentences[" + i + "].ChannelId: " +
                        jsonResult.getJSONObject("Result").getJSONArray("Sentences").getJSONObject(i).getString("ChannelId"));
                    System.out.println("Result.Sentences[" + i + "].SpeechRate: " +
                        jsonResult.getJSONObject("Result").getJSONArray("Sentences").getJSONObject(i).getString("SpeechRate"));
                    System.out.println("Result.Sentences[" + i + "].EmotionValue: " +
                        jsonResult.getJSONObject("Result").getJSONArray("Sentences").getJSONObject(i).getString("EmotionValue"));
                }
            }
            else if(matcherClient.matches()) {
                System.out.println("A status code that starts with 4 indicates a client error...");
            }
            else if(matcherServer.matches()) {
                System.out.println("A status code that starts with 5 indicates a server error...");
            }
            else {
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}