阅读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)_智能语音交互-阿里云