閱讀838 返回首頁    go 阿裏雲


API使用__錄音文件識別_語音識別(ASR)_智能語音交互-阿裏雲

“錄音文件識別”API包括兩部分:POST方式的“請求調用接口”,GET方式的“結果查詢接口”。

請求調用接口

提交識別請求以獲取id。

URL說明

協議 URL 方法 參數
HTTPS nlsapi.aliyun.com/transcriptions POST JSON字符串

輸入參數

“請求調用接口”的關鍵請求參數,以json格式放置於Https Body內,並作為數加驗證的body參數進行加密。

  1. {
  2. "app_key": "***",
  3. "oss_link": "***",
  4. "valid_times": [
  5. {
  6. "begin_time": 200,
  7. "end_time":2000,
  8. "channel_id": 0
  9. }
  10. ]
  11. }
  • 請求參數JSON字符串:
屬性 值類型 是否必須 說明
app_key String 業務方或者業務場景的標記
oss_link String 語音文件存放的OSS link地址
valid_times List< ValidTime > 有效時間段信息,用來排查一些不必要的時間段
  • 有效時間段ValidTime描述:
屬性 值類型 是否必須 說明
begin_time Int 有效時間段的起始點時間偏移(單位: ms)
end_time Int 有效時間段的結束點時間偏移(單位: ms)
channel_id Int 有效時間段的作用音軌序號(從0開始)
  • 數加驗證字符串:

數加驗證字符串以json格式放置於Https headers內。數加驗證過程見“官方服務API校驗規範”。使用過程見完整示例。

  1. {
  2. "Content-Type": "application/json",
  3. "Accept": "application/json",
  4. "date": gmtTime,
  5. "Authorization": authorization
  6. }

輸出參數

  1. {
  2. "id": "***"
  3. }

參數說明:

  • 返回HTTP狀態: 201 Created
  • 返回參數JSON字符串:
屬性 值類型 是否必須 說明
id String 識別任務ID

結果查詢接口

在提交完識別請求後,調用方將可以按照如下接口輪詢結果。

URL說明

協議 URL 方法 參數
HTTPS nlsapi.aliyun.com/transcriptions/< id > GET

輸入參數

用戶通過id調用“結果查詢”接口可獲取識別結果,在接口調用過程時,需要設置一定的查詢時間間隔,可參考完整示例

  • 請求參數:

id為識別任務ID。

  • 數加驗證字符串:

數加驗證字符串以json格式放置於Https headers內。數加驗證過程見“官方服務API校驗規範”。使用過程見完整示例。

  1. {
  2. "Content-Type": "application/json",
  3. "Accept": "application/json",
  4. "date": gmtTime,
  5. "Authorization": authorization
  6. }

輸出參數

正常返回

  1. {
  2. "id": "***",
  3. "status": "SUCCEED",
  4. "result": [
  5. {
  6. "channel_id": 0,
  7. "begin_time": 700,
  8. "end_time": 3120,
  9. "text": "你好,很高興為您服務"
  10. }
  11. ......
  12. ]
  13. }

正在識別

  1. {
  2. "id":"2e2bf1fbe4d34dab8b9e36488d0fa1e2",
  3. "status":"RUNNING"
  4. }

異常返回

  1. {
  2. "error_message": "UNSUPPORTED_SAMPLE_RATE",
  3. "id": "***",
  4. "status": "FAILED",
  5. "status_code": 400
  6. }

參數說明:

  • 返回HTTP狀態: 200 OK
  • 返回參數JSON字符串:
屬性 值類型 是否必須 說明
id String 識別任務ID
status String 該識別任務的當前狀態, 三種取值:RUNNING, SUCCEED, FAILED
status_code Int 錯誤碼。當status為FAILED時存在。
error_message String 對錯誤狀態的進一步描述。當status為FAILED時存在
result List< SentenceResult> 識別的結果數據。當status為SUCCEED時存在
  • 錯誤碼status_code描述:
狀態碼 說明
200 成功
400 無效的請求
401 需要鑒權信息
403 鑒權失敗
404 不存在
408 請求超時
422 請求內容有誤
429 超出最大並發
500 服務器內部出錯
503 服務不可用
  • 單句結果SentenceResult描述:
屬性 值類型 是否必須 說明
channel_id Int 該句所屬音軌ID
begin_time Int 該句的起始時間偏移(單位: ms)
end_time Int 該句的結束時間偏移(單位: ms)
text String 該句的識別文本結果

完整示例

Java Demo 下載地址

  • 語音文件識別服務demo入口
  1. package com.alibaba.idst.nls;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.idst.nls.utils.*;
  4. public class TranscriptionDemo {
  5. /**
  6. * 服務url
  7. * */
  8. private static String url = "https://nlsapi.aliyun.com/transcriptions";
  9. private static RequestBody body = new RequestBody();
  10. private static HttpUtil request = new HttpUtil();
  11. public static void main(String[] args) throws InterruptedException {
  12. //設置請求參數
  13. body.setApp_key("xxx");
  14. body.setOss_link("https://aliyun-nls.oss.aliyuncs.com/asr/fileASR/examples/nls-sample.wav");
  15. body.addValid_time(100,2000,0); //validtime 可選字段 設置的是語音文件中希望識別的內容,begintime,endtime以及channel
  16. body.addValid_time(100,2000,1);
  17. String ak_id = "xxx";
  18. String ak_secret = "xxx";
  19. System.out.println("Recognize begin!");
  20. /*
  21. * 發送錄音轉寫請求
  22. * **/
  23. String bodyString;
  24. bodyString = JSON.toJSONString(body);
  25. String postResult = request.sendPost(url,bodyString,ak_id,ak_secret);
  26. System.out.println("response is:"+postResult);
  27. /*
  28. * 通過TaskId獲取識別結果
  29. * **/
  30. String TaskId = JSON.parseObject(postResult).getString("id");
  31. String status = "RUNNING";
  32. String getResult = "";
  33. while (!status.equals("RUNNING")){
  34. Thread.sleep(3000);
  35. getResult = request.sendGet(url,TaskId,ak_id,ak_secret);
  36. status = JSON.parseObject(getResult).getString("status");
  37. System.out.println("response is:"+getResult);
  38. }
  39. System.out.println("Recognize over!");
  40. }
  41. }
  • RequestBody類,語音識別服務請求中數加鑒權所需的body參數,也是HTTPS請求的data部分。
  1. package com.alibaba.idst.nls.utils;
  2. import java.util.*;
  3. public class RequestBody {
  4. private String app_key = null; //appkey 應用的key
  5. private String oss_link = null; //語音文件存儲地址
  6. private List<validTime> valid_times =null; //有效時間段ValidTime描述,可選字段
  7. public class validTime{
  8. private int begin_time;
  9. private int end_time;
  10. private int channel_id;
  11. public int getBegin_time() {
  12. return begin_time;
  13. }
  14. public void setBegin_time(int begin_time) {
  15. this.begin_time = begin_time;
  16. }
  17. public int getEnd_time() {
  18. return end_time;
  19. }
  20. public void setEnd_time(int end_time) {
  21. this.end_time = end_time;
  22. }
  23. public int getChannel_id() {
  24. return channel_id;
  25. }
  26. public void setChannel_id(int channel_id) {
  27. this.channel_id = channel_id;
  28. }
  29. }
  30. public void setApp_key(String appKey){
  31. app_key = appKey;
  32. }
  33. public void setOss_link(String fileLine){
  34. oss_link = fileLine;
  35. }
  36. public void addValid_time(int beginTime,int endTime,int channelId){
  37. if(valid_times == null){
  38. valid_times = new ArrayList<validTime>();
  39. }
  40. validTime valid_time = new validTime();
  41. valid_time.setBegin_time(beginTime);
  42. valid_time.setEnd_time(endTime);
  43. valid_time.setChannel_id(channelId);
  44. valid_times.add(valid_time);
  45. }
  46. public List<validTime> getValid_times() {
  47. return valid_times;
  48. }
  49. public String getOss_link() {
  50. return oss_link;
  51. }
  52. public String getApp_key() {
  53. return app_key;
  54. }
  55. }
  • HttpUtil類,實現數加鑒權過程,並將其作為HTTPS請求的header部分。實現POST方式的請求識別方法和GET方式的結果查詢方法。
  1. package com.alibaba.idst.nls.utils;
  2. import java.io.*;
  3. import java.net.URL;
  4. import java.net.URLConnection;
  5. import java.security.MessageDigest;
  6. import java.text.SimpleDateFormat;
  7. import java.util.Date;
  8. import java.util.Locale;
  9. import javax.crypto.spec.SecretKeySpec;
  10. import sun.misc.BASE64Encoder;
  11. import javax.crypto.Mac;
  12. @SuppressWarnings("restriction")
  13. public class HttpUtil {
  14. /*
  15. * 計算MD5+BASE64
  16. */
  17. public static String MD5Base64(String s) throws UnsupportedEncodingException {
  18. if (s == null)
  19. return null;
  20. String encodeStr = "";
  21. //string 編碼必須為utf-8
  22. byte[] utfBytes = s.getBytes("UTF-8");
  23. MessageDigest mdTemp;
  24. try {
  25. mdTemp = MessageDigest.getInstance("MD5");
  26. mdTemp.update(utfBytes);
  27. byte[] md5Bytes = mdTemp.digest();
  28. BASE64Encoder b64Encoder = new BASE64Encoder();
  29. encodeStr = b64Encoder.encode(md5Bytes);
  30. } catch (Exception e) {
  31. throw new Error("Failed to generate MD5 : " + e.getMessage());
  32. }
  33. return encodeStr;
  34. }
  35. /*
  36. * 計算 HMAC-SHA1
  37. */
  38. public static String HMACSha1(String data, String key) {
  39. String result;
  40. try {
  41. SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
  42. Mac mac = Mac.getInstance("HmacSHA1");
  43. mac.init(signingKey);
  44. byte[] rawHmac = mac.doFinal(data.getBytes());
  45. result = (new BASE64Encoder()).encode(rawHmac);
  46. } catch (Exception e) {
  47. throw new Error("Failed to generate HMAC : " + e.getMessage());
  48. }
  49. return result;
  50. }
  51. /*
  52. * 等同於javaScript中的 new Date().toUTCString();
  53. */
  54. public static String toGMTString(Date date) {
  55. SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);
  56. df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));
  57. return df.format(date);
  58. }
  59. /*
  60. * 發送POST請求
  61. */
  62. public static String sendPost(String url, String body, String ak_id, String ak_secret) {
  63. PrintWriter out = null;
  64. BufferedReader in = null;
  65. String result = "";
  66. try {
  67. URL realUrl = new URL(url);
  68. /*
  69. * http header 參數
  70. */
  71. String method = "POST";
  72. String accept = "application/json";
  73. String content_type = "application/json";
  74. String path = realUrl.getFile();
  75. String date = toGMTString(new Date());
  76. // 1.對body做MD5+BASE64加密
  77. String bodyMd5 = MD5Base64(body);
  78. String stringToSign = method + "n" + accept + "n" + bodyMd5 + "n" + content_type + "n" + date ;
  79. // 2.計算 HMAC-SHA1
  80. String signature = HMACSha1(stringToSign, ak_secret);
  81. // 3.得到 authorization header
  82. String authHeader = "Dataplus " + ak_id + ":" + signature;
  83. // 打開和URL之間的連接
  84. URLConnection conn = realUrl.openConnection();
  85. // 設置通用的請求屬性
  86. conn.setRequestProperty("accept", accept);
  87. conn.setRequestProperty("content-type", content_type);
  88. conn.setRequestProperty("date", date);
  89. conn.setRequestProperty("Authorization", authHeader);
  90. // 發送POST請求必須設置如下兩行
  91. conn.setDoOutput(true);
  92. conn.setDoInput(true);
  93. // 獲取URLConnection對象對應的輸出流
  94. out = new PrintWriter(conn.getOutputStream());
  95. // 發送請求參數
  96. out.print(body);
  97. // flush輸出流的緩衝
  98. out.flush();
  99. // 定義BufferedReader輸入流來讀取URL的響應
  100. in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  101. String line;
  102. while ((line = in.readLine()) != null) {
  103. result += line;
  104. }
  105. } catch (Exception e) {
  106. System.out.println("發送 POST 請求出現異常!" + e);
  107. e.printStackTrace();
  108. }
  109. // 使用finally塊來關閉輸出流、輸入流
  110. finally {
  111. try {
  112. if (out != null) {
  113. out.close();
  114. }
  115. if (in != null) {
  116. in.close();
  117. }
  118. } catch (IOException ex) {
  119. ex.printStackTrace();
  120. }
  121. }
  122. return result;
  123. }
  124. /*
  125. * GET請求
  126. */
  127. public static String sendGet(String url, String task_id,String ak_id, String ak_secret) {
  128. String result = "";
  129. BufferedReader in = null;
  130. try {
  131. URL realUrl = new URL(url+"/"+task_id);
  132. /*
  133. * http header 參數
  134. */
  135. String method = "GET";
  136. String accept = "application/json";
  137. String content_type = "application/json";
  138. String path = realUrl.getFile();
  139. String date = toGMTString(new Date());
  140. // 1.對body做MD5+BASE64加密
  141. //String bodyMd5 = MD5Base64("");
  142. String stringToSign = method + "n" + accept + "n" + "" + "n" + content_type + "n" + date;
  143. // 2.計算 HMAC-SHA1
  144. String signature = HMACSha1(stringToSign, ak_secret);
  145. // 3.得到 authorization header
  146. String authHeader = "Dataplus " + ak_id + ":" + signature;
  147. // 打開和URL之間的連接
  148. URLConnection connection = realUrl.openConnection();
  149. // 設置通用的請求屬性
  150. connection.setRequestProperty("accept", accept);
  151. connection.setRequestProperty("content-type", content_type);
  152. connection.setRequestProperty("date", date);
  153. connection.setRequestProperty("Authorization", authHeader);
  154. // 建立實際的連接
  155. connection.connect();
  156. // 定義 BufferedReader輸入流來讀取URL的響應
  157. in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  158. String line;
  159. while ((line = in.readLine()) != null) {
  160. result += line;
  161. }
  162. } catch (Exception e) {
  163. System.out.println("發送GET請求出現異常!" + e);
  164. e.printStackTrace();
  165. }
  166. // 使用finally塊來關閉輸入流
  167. finally {
  168. try {
  169. if (in != null) {
  170. in.close();
  171. }
  172. } catch (Exception e) {
  173. e.printStackTrace();
  174. }
  175. }
  176. return result;
  177. }
  178. }

最後更新:2016-11-23 17:16:08

  上一篇:go OPUS格式語音編解碼__一句話識別_語音識別(ASR)_智能語音交互-阿裏雲
  下一篇:go 批量合成工具__語音合成(TTS)_智能語音交互-阿裏雲