All Products
Search
Document Center

Java demo

Last Updated: May 18, 2020

Note:

  • Read API reference before using the SDK.
  • The SDK in this topic applies only to Intelligent Speech Interaction V2.0 that Alibaba Cloud published on July 5, 2018. If you have activated an earlier version of Intelligent Speech Interaction, activate Intelligent Speech Interaction V2.0 before using the SDK.

SDK instructions

The Java demo of the recording file recognition service uses the CommonRequest method of the Alibaba Cloud SDK for Java to send 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 about how to use the CommonRequest method of the Alibaba Cloud SDK for Java, see Use CommonRequest in Java SDK Developer Guide.

Note: The Alibaba Cloud SDK for Java does not support development in Android.

Add Java dependencies

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

  1. <dependency>
  2. <groupId>com.aliyun</groupId>
  3. <artifactId>aliyun-java-sdk-core</artifactId>
  4. <version>3.7.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>fastjson</artifactId>
  9. <version>1.2.49</version>
  10. </dependency>

Demo instructions

Note: The recording file in the demo is a pulse-code modulation (PCM) file sampled at 16 kHz. The demo uses a universal model in the console. If you use your own recording file, specify its audio coding format and audio sampling rate and select an appropriate model in the console. For more information about how to select a model, see Manage projects in Console User Guide.

nls-sample-16k.wav

Alibaba Cloud authentication

When using the SDK, you need to use your Alibaba Cloud account to authenticate the client for all API operations. You need to use the AccessKey ID and AccessKey secret of your Alibaba Cloud account to call the Alibaba Cloud SDK for Java and create a client. For more information about how to obtain your AccessKey information, see Activate Intelligent Speech Interaction in Quick Start. Use the following sample code:

  1. final String accessKeyId = "Your AccessKey ID";
  2. final String accessKeySecret = "Your AccessKey secret";
  3. /**
  4. * Specify the region ID.
  5. */
  6. final String regionId = "ap-southeast-1";
  7. final String endpointName = "ap-southeast-1";
  8. final String product = "nls-filetrans";
  9. final String domain = "filetrans.ap-southeast-1.aliyuncs.com";
  10. IAcsClient client;
  11. // Specify the endpoint of the service.
  12. DefaultProfile.addEndpoint(endpointName, regionId, product, domain);
  13. // Create a DefaultAcsClient instance and initialize it.
  14. DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
  15. 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 Request parameters in API reference. You need to set only the parameters in the JSON-formatted string and use the default values of parameters for other methods.

  1. /**
  2. * Create a CommonRequest object and set request parameters.
  3. */
  4. CommonRequest postRequest = new CommonRequest();
  5. postRequest.setDomain("filetrans.ap-southeast-1.aliyuncs.com"); // The endpoint of the service. The value is fixed.
  6. postRequest.setVersion("2019-08-23"); // The version of the API. The value is fixed.
  7. postRequest.setAction("SubmitTask"); // The operation that you want to perform. The value is fixed.
  8. postRequest.setProduct("nls-filetrans"); // The name of the service. The value is fixed.
  9. // Set parameters for the recording file recognition request and add request parameters to the request body as a JSON-formatted string.
  10. JSONObject taskObject = new JSONObject();
  11. taskObject.put("appkey", "Your appkey"); // The appkey of your project created in the console.
  12. taskObject.put("file_link", "Your recording file URL"); // The URL of the recording file to be recognized.
  13. taskObject.put(KEY_VERSION, "4.0"); // 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.
  14. String task = taskObject.toJSONString();
  15. postRequest.putBodyParameter("Task", task); // The request body, which includes request parameters in a JSON-formatted string.
  16. postRequest.setMethod(MethodType.POST); // The POST method used to send the request.
  17. /**
  18. * Send the recording file recognition request.
  19. */
  20. String taskId = ""; // Obtain the ID of the recording file recognition task. You can use the task ID to query the recognition result.
  21. CommonResponse postResponse = client.getCommonResponse(postRequest);
  22. if (postResponse.getHttpStatus() == 200) {
  23. JSONObject result = JSONObject.parseObject(postResponse.getData());
  24. String statusText = result.getString("StatusText");
  25. if ("SUCCESS".equals(statusText)) {
  26. System.out.println("Success response to the recording file recognition request: " + result.toJSONString());
  27. taskId = result.getString("TaskId");
  28. }
  29. else {
  30. System.out.println("Error response to the recording file recognition request: " + result.toJSONString());
  31. return;
  32. }
  33. }
  34. else {
  35. System.err.println("The recording file recognition request fails. HTTP status code: " + postResponse.getHttpStatus());
  36. System.err.println("Error response to the recording file recognition request: " + JSONObject.toJSONString(postResponse));
  37. return;
  38. }

Query request for the recording file recognition result

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

  1. /**
  2. * Create a CommonRequest object and specify the task ID.
  3. */
  4. CommonRequest getRequest = new CommonRequest();
  5. getRequest.setDomain("filetrans.ap-southeast-1.aliyuncs.com"); // The endpoint of the service. The value is fixed.
  6. getRequest.setVersion("2019-08-23"); // The version of the API. The value is fixed.
  7. getRequest.setAction("GetTaskResult"); // The operation that you want to perform. The value is fixed.
  8. getRequest.setProduct("nls-filetrans"); // The name of the service. The value is fixed.
  9. getRequest.putQueryParameter("TaskId", taskId); // The ID of the recognition task.
  10. getRequest.setMethod(MethodType.GET); // The GET method used to send the request.
  11. /**
  12. * Send the query request for the recording file recognition result.
  13. * Use the polling method to query the recognition result. The polling runs until the status message that the server returns is SUCCESS, SUCCESS_WITH_NO_VALID_FRAGMENT, or an error message.
  14. */
  15. String statusText = "";
  16. while (true) {
  17. CommonResponse getResponse = client.getCommonResponse(getRequest);
  18. if (getResponse.getHttpStatus() != 200) {
  19. System.err.println("Failed to query the recording file recognition result. HTTP status code: " + getResponse.getHttpStatus());
  20. System.err.println("Error response to the query request for the recording file recognition result: " + getResponse.getData());
  21. break;
  22. }
  23. JSONObject result = JSONObject.parseObject(getResponse.getData());
  24. System.out.println("Queried recording file recognition result: " + result.toJSONString());
  25. statusText = result.getString("StatusText");
  26. if ("RUNNING".equals(statusText) || "QUEUEING".equals(statusText)) {
  27. // Continue the polling.
  28. Thread.sleep(10000);
  29. }
  30. else {
  31. break;
  32. }
  33. }
  34. if ("SUCCESS".equals(statusText) || "SUCCESS_WITH_NO_VALID_FRAGMENT".equals(statusText)) {
  35. System.out.println("The recording file is recognized.") ;
  36. }
  37. else {
  38. System.err.println("Failed to recognize the recording file.") ;
  39. }

Complete sample code

  1. import com.alibaba.fastjson.JSONObject;
  2. import com.aliyuncs.CommonRequest;
  3. import com.aliyuncs.CommonResponse;
  4. import com.aliyuncs.DefaultAcsClient;
  5. import com.aliyuncs.IAcsClient;
  6. import com.aliyuncs.exceptions.ClientException;
  7. import com.aliyuncs.http.MethodType;
  8. import com.aliyuncs.profile.DefaultProfile;
  9. public class FileTransJavaDemo {
  10. // The constant parameters, such as the region ID. Do not modify their values.
  11. public static final String REGIONID = "ap-southeast-1";
  12. public static final String ENDPOINTNAME = "ap-southeast-1";
  13. public static final String PRODUCT = "nls-filetrans";
  14. public static final String DOMAIN = "filetrans.ap-southeast-1.aliyuncs.com";
  15. public static final String API_VERSION = "2019-08-23";
  16. public static final String POST_REQUEST_ACTION = "SubmitTask";
  17. public static final String GET_REQUEST_ACTION = "GetTaskResult";
  18. // The keys of request parameters.
  19. public static final String KEY_APP_KEY = "appkey";
  20. public static final String KEY_FILE_LINK = "file_link";
  21. public static final String KEY_VERSION = "version";
  22. public static final String KEY_ENABLE_WORDS = "enable_words";
  23. // The keys of response parameters.
  24. public static final String KEY_TASK = "Task";
  25. public static final String KEY_TASK_ID = "TaskId";
  26. public static final String KEY_STATUS_TEXT = "StatusText";
  27. public static final String KEY_RESULT = "Result";
  28. // The status values.
  29. public static final String STATUS_SUCCESS = "SUCCESS";
  30. private static final String STATUS_RUNNING = "RUNNING";
  31. private static final String STATUS_QUEUEING = "QUEUEING";
  32. // Create and authenticate a client.
  33. IAcsClient client;
  34. public FileTransJavaDemo(String accessKeyId, String accessKeySecret) {
  35. // Specify the endpoint of the service.
  36. try {
  37. DefaultProfile.addEndpoint(ENDPOINTNAME, REGIONID, PRODUCT, DOMAIN);
  38. } catch (ClientException e) {
  39. e.printStackTrace();
  40. }
  41. // Create a DefaultAcsClient instance and initialize it.
  42. DefaultProfile profile = DefaultProfile.getProfile(REGIONID, accessKeyId, accessKeySecret);
  43. this.client = new DefaultAcsClient(profile);
  44. }
  45. public String submitFileTransRequest(String appKey, String fileLink) {
  46. /**
  47. * 1. Create a CommonRequest object and set request parameters.
  48. */
  49. CommonRequest postRequest = new CommonRequest();
  50. // The endpoint of the service.
  51. postRequest.setDomain(DOMAIN);
  52. // The version of the API, in YYYY-MM-DD format.
  53. postRequest.setVersion(API_VERSION);
  54. // The operation that you want to perform.
  55. postRequest.setAction(POST_REQUEST_ACTION);
  56. // The name of the service.
  57. postRequest.setProduct(PRODUCT);
  58. /**
  59. * 2. Set parameters for the recording file recognition request and add request parameters to the request body as a JSON-formatted string.
  60. */
  61. JSONObject taskObject = new JSONObject();
  62. // The appkey of the project created in the console.
  63. taskObject.put(KEY_APP_KEY, appKey);
  64. // The URL of the recording file to be recognized.
  65. taskObject.put(KEY_FILE_LINK, fileLink);
  66. // 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.
  67. taskObject.put(KEY_VERSION, "4.0");
  68. // 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.
  69. taskObject.put(KEY_ENABLE_WORDS, true);
  70. String task = taskObject.toJSONString();
  71. System.out.println(task);
  72. // The request body, which includes request parameters in a JSON-formatted string.
  73. postRequest.putBodyParameter(KEY_TASK, task);
  74. // The POST method used to send the request.
  75. postRequest.setMethod(MethodType.POST);
  76. /**
  77. * 3. Send the recording file recognition request. Obtain the ID of the recording file recognition task. You can use the task ID to query the recognition result.
  78. */
  79. String taskId = null;
  80. try {
  81. CommonResponse postResponse = client.getCommonResponse(postRequest);
  82. System.err.println("Response to the recording file recognition request: " + postResponse.getData());
  83. if (postResponse.getHttpStatus() == 200) {
  84. JSONObject result = JSONObject.parseObject(postResponse.getData());
  85. String statusText = result.getString(KEY_STATUS_TEXT);
  86. if (STATUS_SUCCESS.equals(statusText)) {
  87. taskId = result.getString(KEY_TASK_ID);
  88. }
  89. }
  90. } catch (ClientException e) {
  91. e.printStackTrace();
  92. }
  93. return taskId;
  94. }
  95. public String getFileTransResult(String taskId) {
  96. /**
  97. * 1. Create a CommonRequest object and specify the task ID.
  98. */
  99. CommonRequest getRequest = new CommonRequest();
  100. // The endpoint of the service.
  101. getRequest.setDomain(DOMAIN);
  102. // The version of the API.
  103. getRequest.setVersion(API_VERSION);
  104. // The operation that you want to perform.
  105. getRequest.setAction(GET_REQUEST_ACTION);
  106. // The name of the service.
  107. getRequest.setProduct(PRODUCT);
  108. // The ID of the recognition task.
  109. getRequest.putQueryParameter(KEY_TASK_ID, taskId);
  110. // The GET method used to send the request.
  111. getRequest.setMethod(MethodType.GET);
  112. /**
  113. * 2. Send the query request for the recording file recognition result.
  114. * Use the polling method to query the recognition result. The polling runs until the status message that the server returns is SUCCESS or an error message.
  115. */
  116. String result = null;
  117. while (true) {
  118. try {
  119. CommonResponse getResponse = client.getCommonResponse(getRequest);
  120. System.err.println("Queried recording file recognition result: " + getResponse.getData());
  121. if (getResponse.getHttpStatus() != 200) {
  122. break;
  123. }
  124. JSONObject rootObj = JSONObject.parseObject(getResponse.getData());
  125. String statusText = rootObj.getString(KEY_STATUS_TEXT);
  126. if (STATUS_RUNNING.equals(statusText) || STATUS_QUEUEING.equals(statusText)) {
  127. // Continue the polling. You need to set the polling interval.
  128. Thread.sleep(3000);
  129. }
  130. else {
  131. // If the status message indicates that the task is successful, the recognition result is returned. If the status message indicates that an error occurs, an empty result is returned.
  132. if (STATUS_SUCCESS.equals(statusText)) {
  133. result = rootObj.getString(KEY_RESULT);
  134. }
  135. break;
  136. }
  137. } catch (Exception e) {
  138. e.printStackTrace();
  139. }
  140. }
  141. return result;
  142. }
  143. public static void main(String args[]) throws Exception {
  144. if (args.length < 3) {
  145. System.err.println("FileTransJavaDemo need params: <AccessKey Id> <AccessKey Secret> <app-key>");
  146. }
  147. final String accessKeyId = args[0];
  148. final String accessKeySecret = args[1];
  149. final String appKey = args[2];
  150. String fileLink = "https://aliyun-nls.oss-cn-hangzhou.aliyuncs.com/asr/fileASR/examples/nls-sample-16k.wav";
  151. FileTransJavaDemo demo = new FileTransJavaDemo(accessKeyId, accessKeySecret);
  152. // Step 1: Send the recording file recognition request and obtain the task ID for subsequent recognition result polling.
  153. String taskId = demo.submitFileTransRequest(appKey, fileLink);
  154. if (taskId != null) {
  155. System.out.println("The recording file recognition request is successful. task_id: " + taskId);
  156. }
  157. else {
  158. System.out.println("The recording file recognition request fails.") ;
  159. return;
  160. }
  161. // Step 2: Poll the recognition result based on the task ID.
  162. String result = demo.getFileTransResult(taskId);
  163. if (result != null) {
  164. System.out.println("Queried recording file recognition result: " + result);
  165. }
  166. else {
  167. System.out.println("Failed to query the recording file recognition result.") ;
  168. }
  169. }
  170. }

Note: If you use the callback method, you need to set the enable_callback and callback_url parameters in the JSON-formatted string of the request body.

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

Callback method: You can also use the callback method to query the recording file recognition result. The following sample code is for reference only. Assume that the callback URL is http://IP address:port/filetrans/callback/result.

  1. package com.example.filetrans;
  2. import com.alibaba.fastjson.JSONObject;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RequestMethod;
  5. import org.springframework.web.bind.annotation.RestController;
  6. import javax.servlet.ServletInputStream;
  7. import javax.servlet.http.HttpServletRequest;
  8. import java.io.IOException;
  9. import java.util.regex.Matcher;
  10. import java.util.regex.Pattern;
  11. @RequestMapping("/filetrans/callback")
  12. @RestController
  13. public class FiletransCallBack {
  14. // Status codes that start with 4 indicate client errors.
  15. private static final Pattern PATTERN_CLIENT_ERR = Pattern.compile("4105[0-9]*");
  16. // Status codes that start with 5 indicate server errors.
  17. private static final Pattern PATTERN_SERVER_ERR = Pattern.compile("5105[0-9]*");
  18. // You must use the POST method.
  19. @RequestMapping(value = "result", method = RequestMethod.POST)
  20. public void GetResult(HttpServletRequest request) {
  21. byte [] buffer = new byte[request.getContentLength()];
  22. ServletInputStream in = null;
  23. try {
  24. in = request.getInputStream();
  25. in.read(buffer, 0 ,request.getContentLength());
  26. in.close();
  27. // Obtain the recording file recognition result in JSON format.
  28. String result = new String(buffer);
  29. JSONObject jsonResult = JSONObject.parseObject(result);
  30. // Parse and return the recognition result.
  31. System.out.println("Queried recording file recognition result: " + result);
  32. System.out.println("TaskId: " + jsonResult.getString("TaskId"));
  33. System.out.println("StatusCode: " + jsonResult.getString("StatusCode"));
  34. System.out.println("StatusText: " + jsonResult.getString("StatusText"));
  35. Matcher matcherClient = PATTERN_CLIENT_ERR.matcher(jsonResult.getString("StatusCode"));
  36. Matcher matcherServer = PATTERN_SERVER_ERR.matcher(jsonResult.getString("StatusCode"));
  37. // 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.
  38. if("21050000".equals(jsonResult.getString("StatusCode"))) {
  39. System.out.println("RequestTime: " + jsonResult.getString("RequestTime"));
  40. System.out.println("SolveTime: " + jsonResult.getString("SolveTime"));
  41. System.out.println("BizDuration: " + jsonResult.getString("BizDuration"));
  42. System.out.println("Result.Sentences.size: " +
  43. jsonResult.getJSONObject("Result").getJSONArray("Sentences").size());
  44. for (int i = 0; i < jsonResult.getJSONObject("Result").getJSONArray("Sentences").size(); i++) {
  45. System.out.println("Result.Sentences[" + i + "].BeginTime: " +
  46. jsonResult.getJSONObject("Result").getJSONArray("Sentences").getJSONObject(i).getString("BeginTime"));
  47. System.out.println("Result.Sentences[" + i + "].EndTime: " +
  48. jsonResult.getJSONObject("Result").getJSONArray("Sentences").getJSONObject(i).getString("EndTime"));
  49. System.out.println("Result.Sentences[" + i + "].SilenceDuration: " +
  50. jsonResult.getJSONObject("Result").getJSONArray("Sentences").getJSONObject(i).getString("SilenceDuration"));
  51. System.out.println("Result.Sentences[" + i + "].Text: " +
  52. jsonResult.getJSONObject("Result").getJSONArray("Sentences").getJSONObject(i).getString("Text"));
  53. System.out.println("Result.Sentences[" + i + "].ChannelId: " +
  54. jsonResult.getJSONObject("Result").getJSONArray("Sentences").getJSONObject(i).getString("ChannelId"));
  55. System.out.println("Result.Sentences[" + i + "].SpeechRate: " +
  56. jsonResult.getJSONObject("Result").getJSONArray("Sentences").getJSONObject(i).getString("SpeechRate"));
  57. System.out.println("Result.Sentences[" + i + "].EmotionValue: " +
  58. jsonResult.getJSONObject("Result").getJSONArray("Sentences").getJSONObject(i).getString("EmotionValue"));
  59. }
  60. }
  61. else if(matcherClient.matches()) {
  62. System.out.println("A status code that starts with 4 indicates a client error...") ;
  63. }
  64. else if(matcherServer.matches()) {
  65. System.out.println("A status code that starts with 5 indicates a server error...") ;
  66. }
  67. else {
  68. }
  69. } catch (IOException e) {
  70. e.printStackTrace();
  71. }
  72. }
  73. }