全部产品

语音合成REST接口

更新时间:2017-08-04 17:21:13   分享:   

1. 简介

语音合成REST API支持以POST方式上传UTF-8编码的合成文本。服务端支持以16bitpcm、alaw编码或16bit wav/pcm文件返回生成语音。语音合成服务的请求地址为:https://nlsapi.aliyun.com/speak

2. 请求格式

  • 语音合成请求实例
  1. POST http://nlsapi.aliyun.com/speak?encode_type=pcm&voice_name=xiaoyun&volume=50
  2. Date: Tue, 21 Mar 2017 11:42:00 GMT
  3. Content-type: text/plain
  4. Authorization: Dataplus *****
  5. Accept: audio/pcm, application/json
  6. Content-Length: 36
  7. 需要被转换的文本

2.1 参数配置

语音合成服务在处理请求时,将在URL地址中检查如下参数。若参数未设置,将以缺省值合成语音。

名称 类型 需求 缺省值 描述
encode_type String 选填 pcm 合成语音的编码格式,支持pcm/wav/mp3/alaw
voice_name String 选填 xiaoyun xiaogang - 男,xiaoyun - 女
volume int 选填 50 0~100
sample_rate int 选填 16000 抽样频率率 8000/16000
speech_rate int 选填 0 语速 -500~500
pitch_rate int 选填 0 语调 -500~500
tts_nus int 选填 1 0 - 通过参数合成语音,1 - 拼接原始录音
background_music_id int 选填 播放语音时可选背景音乐,0,1
background_music_offset int 选填 0 背景音乐播放偏移时长,毫秒。当启用背景音乐时生效
background_music_volume int 选填 50 背景音乐音量,当启用背景音乐时生效,0~100

2.2 语音合成文本

请以UTF-8格式编码后将需要合成的语音文本在POST body中上传,单次请求限制为200个UTF-8字符,即每个汉字、数字、字母都算一个字符。

2.3 HTTP Header

名称 类型 需求 描述
Authorization String 必填 鉴权, 详见 2.3.1
Content-type String 必填 text/plain
Accept String 必填 固定为audio/*, application/json,请将星号替换为所需编码格式,pcm/wav/alaw
Date String 必填 鉴权,HTTP 1.1协议中规定的GMT时间,例如:Wed, 05 Sep. 2012 23:00:00 GMT

2.3.1 Authorization Header

调用阿里巴巴智能语音交互平台的任何功能前都需经过严格的鉴权验证,参见“官方服务API校验规范”。在处理用户请求前,服务端会校验Authorization Header以确保用户请求在传输过程中没有被恶意篡改或替换。

  1. Authorization: Dataplus access_id:signature

Authorization以固定字符串Dataplus开头,开发者需要将从阿里云申请到的access_id和经过计算的signature以:分隔并以Base64编码后加入Header。

2.3.1.1 signature的计算

区别于标准的校验规范,计算signature需要首先对语音文件进行MD5和Base64编码。之后将编码结果与Reqeust MethodAcceptContent-TypeDate Header合并产生特征值。最终用阿里云取得的access_key对特征值进行HMAC-SHA1加密生成signature。

  1. // 1.对body进行MD5+BASE64加密
  2. String bodyMd5 = MD5Base64(body);
  3. // 2.特征值
  4. String feature = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date;
  5. // 2.对特征值HMAC-SHA1加密
  6. String signature = HMACSha1(feature, access_secret);
2.3.1.2 计算 MD5+BASE64
  1. public static String MD5Base64(String s) throws UnsupportedEncodingException {
  2. if (s == null)
  3. return null;
  4. String encodeStr = "";
  5. //string 编码必须为utf-8
  6. byte[] utfBytes = s.getBytes("UTF-8");
  7. MessageDigest mdTemp;
  8. try {
  9. mdTemp = MessageDigest.getInstance("MD5");
  10. mdTemp.update(utfBytes);
  11. byte[] md5Bytes = mdTemp.digest();
  12. BASE64Encoder b64Encoder = new BASE64Encoder();
  13. encodeStr = b64Encoder.encode(md5Bytes);
  14. } catch (Exception e) {
  15. throw new Error("Failed to generate MD5 : " + e.getMessage());
  16. }
  17. return encodeStr;
  18. }
2.3.1.3 计算 HMAC-SHA1
  1. public static String HMACSha1(String data, String key) {
  2. String result;
  3. try {
  4. SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
  5. Mac mac = Mac.getInstance("HmacSHA1");
  6. mac.init(signingKey);
  7. byte[] rawHmac = mac.doFinal(data.getBytes());
  8. result = (new BASE64Encoder()).encode(rawHmac);
  9. } catch (Exception e) {
  10. throw new Error("Failed to generate HMAC : " + e.getMessage());
  11. }
  12. return result;
  13. }

2.3.2 Content-Type Header

Content-Type header 规定为text/plain

2.3.3 Accept Header

Accept Header需要允许audio和json两种返回格式。当语音合成成功(包括中途失败),服务器将返回在请求中要求的语音流。请求失败将返回json字符串。

3. 语音合成返回

当语音合成请求成功时,服务端将返回16bit pcm、alaw编码或16bit wav/pcm格式的语音文件。如在合成过程中出现错误,后续语音将不再传输并且没有其他的错误返回。

如果语音合成请求失败,服务端将在response body中返回json格式文件

  1. {
  2. "request_id":"6262b55940044d95afc11d02ddcea377",
  3. "error_code":80103,
  4. "error_message":"authorization failed!"
  5. }

4. 代码示例

4.1 请求DEMO

  1. package com.alibaba.idst.nls;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.BufferedReader;
  5. import java.io.OutputStream;
  6. import java.io.FileReader;
  7. import java.util.UUID;
  8. import com.alibaba.idst.nls.request.TtsRequest;
  9. import com.alibaba.idst.nls.response.HttpResponse;
  10. import com.alibaba.idst.nls.utils.HttpUtil;
  11. import org.slf4j.Logger;
  12. import org.slf4j.LoggerFactory;
  13. public class HttpTtsDemo {
  14. private static Logger logger = LoggerFactory.getLogger(HttpTtsDemo.class);
  15. private String url = "http://nlsapi.aliyun.com/speak?";
  16. private static String tts_text = "薄雾浓云愁永昼。瑞脑消金兽。佳节又重阳,玉枕纱厨,半夜凉初透。东篱把酒黄昏后。有暗香盈袖。莫道不消魂,帘卷西风,人比黄花瘦。";
  17. public static void main(String[] args) throws IOException {
  18. //请使用https://ak-console.aliyun.com/ 页面获取的Access 信息
  19. //请提前开通智能语音服务(https://data.aliyun.com/product/nls)
  20. String ak_id = args[0];
  21. String ak_secret = args[1];
  22. //设置TTS的参数,详细参数说明详见文档部分2.1 参数配置
  23. HttpTtsDemo ttsDemo=new HttpTtsDemo();
  24. TtsRequest ttsRequest = new TtsRequest();
  25. ttsRequest.setEncodeType("wav");
  26. ttsRequest.setVoiceName("xiaoyun");
  27. ttsRequest.setVolume(50);
  28. ttsRequest.setSampleRate(16000);
  29. ttsRequest.setSpeechRate(0);
  30. ttsRequest.setPitchRate(0);
  31. ttsRequest.setTtsNus(1);
  32. ttsRequest.setBackgroundMusicId(0);
  33. ttsRequest.setBackgroundMusicOffset(0);
  34. ttsRequest.setBackgroundMusicVolume(100);
  35. String url = ttsDemo.url+"encode_type="+ttsRequest.getEncodeType()
  36. +"&voice_name="+ttsRequest.getVoiceName()
  37. +"&volume="+ttsRequest.getVolume()
  38. +"&sample_rate="+ttsRequest.getSampleRate()
  39. +"&speech_rate="+ttsRequest.getSpeechRate()
  40. +"&pitch_rate="+ttsRequest.getPitchRate()
  41. +"&tts_nus="+ttsRequest.getTtsNus()
  42. +"&background_music_id="+ttsRequest.getBackgroundMusicId()
  43. +"&background_music_offset="+ttsRequest.getBackgroundMusicOffset()
  44. +"&background_music_volume="+ttsRequest.getBackgroundMusicVolume();
  45. logger.info("TTS request is: {}",url);
  46. String fileName = UUID.randomUUID().toString().replace("-","");
  47. //tts demo 会在项目根目录生产语音文件
  48. HttpResponse response = HttpUtil.sendTtsPost(tts_text,ttsRequest.getEncodeType(), fileName ,url, ak_id, ak_secret);
  49. }
  50. }

4.2 TTS参数类

  1. package com.alibaba.idst.nls.request;
  2. public class TtsRequest {
  3. private String encode_type;
  4. private String voice_name;
  5. private int volume;
  6. private int sample_rate;
  7. private int speech_rate;
  8. private int pitch_rate;
  9. private int tts_nus;
  10. private int background_music_id;
  11. private int background_music_offset;
  12. private int background_music_volume;
  13. public String getEncodeType() {
  14. return encode_type;
  15. }
  16. public void setEncodeType(String encode_type) {
  17. this.encode_type = encode_type;
  18. }
  19. public String getVoiceName() {
  20. return voice_name;
  21. }
  22. public void setVoiceName(String voice_name) {
  23. this.voice_name = voice_name;
  24. }
  25. public int getVolume() {
  26. return volume;
  27. }
  28. public void setVolume(int volume) {
  29. this.volume = volume;
  30. }
  31. public int getSampleRate() {
  32. return sample_rate;
  33. }
  34. public void setSampleRate(int sample_rate) {
  35. this.sample_rate = sample_rate;
  36. }
  37. public int getSpeechRate() {
  38. return speech_rate;
  39. }
  40. public void setSpeechRate(int speech_rate) {
  41. this.speech_rate = speech_rate;
  42. }
  43. public int getPitchRate() {
  44. return pitch_rate;
  45. }
  46. public void setPitchRate(int pitch_rate) {
  47. this.pitch_rate = pitch_rate;
  48. }
  49. public int getTtsNus() {
  50. return tts_nus;
  51. }
  52. public void setTtsNus(int tts_nus) {
  53. this.tts_nus = tts_nus;
  54. }
  55. public int getBackgroundMusicId() {
  56. return background_music_id;
  57. }
  58. public void setBackgroundMusicId(int background_music_id) {
  59. this.background_music_id = background_music_id;
  60. }
  61. public int getBackgroundMusicOffset() {
  62. return background_music_offset;
  63. }
  64. public void setBackgroundMusicOffset(int background_music_offset) {
  65. this.background_music_offset = background_music_offset;
  66. }
  67. public int getBackgroundMusicVolume() {
  68. return background_music_volume;
  69. }
  70. public void setBackgroundMusicVolume(int background_music_volume) {
  71. this.background_music_volume = background_music_volume;
  72. }
  73. }

4.3 请求服务的HttpUtil类

  1. package com.alibaba.idst.nls.utils;
  2. /**
  3. * Created by songsong.sss on 16/5/23.
  4. */
  5. import java.io.*;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.security.MessageDigest;
  9. import java.text.SimpleDateFormat;
  10. import java.util.*;
  11. import javax.crypto.spec.SecretKeySpec;
  12. import com.alibaba.idst.nls.response.HttpResponse;
  13. import javax.crypto.Mac;
  14. import org.slf4j.Logger;
  15. import org.slf4j.LoggerFactory;
  16. import sun.misc.BASE64Encoder;
  17. @SuppressWarnings("restriction")
  18. public class HttpUtil {
  19. static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
  20. /*
  21. * 计算MD5+BASE64
  22. */
  23. public static String MD5Base64(byte[] s) throws UnsupportedEncodingException {
  24. if (s == null){
  25. return null;
  26. }
  27. String encodeStr = "";
  28. //string 编码必须为utf-8
  29. MessageDigest mdTemp;
  30. try {
  31. mdTemp = MessageDigest.getInstance("MD5");
  32. mdTemp.update(s);
  33. byte[] md5Bytes = mdTemp.digest();
  34. BASE64Encoder b64Encoder = new BASE64Encoder();
  35. encodeStr = b64Encoder.encode(md5Bytes);
  36. /* java 1.8以上版本支持
  37. Encoder encoder = Base64.getEncoder();
  38. encodeStr = encoder.encodeToString(md5Bytes);
  39. */
  40. } catch (Exception e) {
  41. throw new Error("Failed to generate MD5 : " + e.getMessage());
  42. }
  43. return encodeStr;
  44. }
  45. /*
  46. * 计算 HMAC-SHA1
  47. */
  48. public static String HMACSha1(String data, String key) {
  49. String result;
  50. try {
  51. SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
  52. Mac mac = Mac.getInstance("HmacSHA1");
  53. mac.init(signingKey);
  54. byte[] rawHmac = mac.doFinal(data.getBytes());
  55. result = (new BASE64Encoder()).encode(rawHmac);
  56. /*java 1.8以上版本支持
  57. Encoder encoder = Base64.getEncoder();
  58. result = encoder.encodeToString(rawHmac);
  59. */
  60. } catch (Exception e) {
  61. throw new Error("Failed to generate HMAC : " + e.getMessage());
  62. }
  63. return result;
  64. }
  65. /*
  66. * 等同于javaScript中的 new Date().toUTCString();
  67. */
  68. public static String toGMTString(Date date) {
  69. SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);
  70. df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));
  71. return df.format(date);
  72. }
  73. /*
  74. * 发送POST请求
  75. */
  76. public static HttpResponse sendAsrPost(byte[] audioData, String audioFormat, int sampleRate, String url,String ak_id, String ak_secret) {
  77. PrintWriter out = null;
  78. BufferedReader in = null;
  79. String result = "";
  80. HttpResponse response = new HttpResponse();
  81. try {
  82. URL realUrl = new URL(url);
  83. /*
  84. * http header 参数
  85. */
  86. String method = "POST";
  87. String accept = "application/json";
  88. String content_type = "audio/"+audioFormat+";samplerate="+sampleRate;
  89. int length = audioData.length;
  90. String date = toGMTString(new Date());
  91. // 1.对body做MD5+BASE64加密
  92. String bodyMd5 = MD5Base64(audioData);
  93. String md52 = MD5Base64(bodyMd5.getBytes());
  94. String stringToSign = method + "\n" + accept + "\n" + md52 + "\n" + content_type + "\n" + date ;
  95. // 2.计算 HMAC-SHA1
  96. String signature = HMACSha1(stringToSign, ak_secret);
  97. // 3.得到 authorization header
  98. String authHeader = "Dataplus " + ak_id + ":" + signature;
  99. // 打开和URL之间的连接
  100. HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
  101. // 设置通用的请求属性
  102. conn.setRequestProperty("accept", accept);
  103. conn.setRequestProperty("content-type", content_type);
  104. conn.setRequestProperty("date", date);
  105. conn.setRequestProperty("Authorization", authHeader);
  106. conn.setRequestProperty("Content-Length", String.valueOf(length));
  107. // 发送POST请求必须设置如下两行
  108. conn.setDoOutput(true);
  109. conn.setDoInput(true);
  110. // 获取URLConnection对象对应的输出流
  111. OutputStream stream = conn.getOutputStream();
  112. // 发送请求参数
  113. stream.write(audioData);
  114. // flush输出流的缓冲
  115. stream.flush();
  116. stream.close();
  117. response.setStatus(conn.getResponseCode());
  118. // 定义BufferedReader输入流来读取URL的响应
  119. if (response.getStatus() ==200){
  120. in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  121. }else {
  122. in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
  123. }
  124. String line;
  125. while ((line = in.readLine()) != null) {
  126. result += line;
  127. }
  128. if (response.getStatus() == 200){
  129. response.setResult(result);
  130. response.setMassage("OK");
  131. }else {
  132. response.setMassage(result);
  133. }
  134. System.out.println("post response status code: ["+response.getStatus()+"], response massage : ["+response.getMassage()+"] ,result :["+response.getResult()+"]");
  135. } catch (Exception e) {
  136. System.out.println("发送 POST 请求出现异常!" + e);
  137. e.printStackTrace();
  138. }
  139. // 使用finally块来关闭输出流、输入流
  140. finally {
  141. try {
  142. if (out != null) {
  143. out.close();
  144. }
  145. if (in != null) {
  146. in.close();
  147. }
  148. } catch (IOException ex) {
  149. ex.printStackTrace();
  150. }
  151. }
  152. return response;
  153. }
  154. /*
  155. * 发送POST请求
  156. */
  157. public static HttpResponse sendTtsPost(String textData,String audioType, String audioName,String url,String ak_id, String ak_secret) {
  158. PrintWriter out = null;
  159. BufferedReader in = null;
  160. String result = "";
  161. HttpResponse response = new HttpResponse();
  162. try {
  163. URL realUrl = new URL(url);
  164. /*
  165. * http header 参数
  166. */
  167. String method = "POST";
  168. String content_type = "text/plain";
  169. String accept = "audio/"+audioType+",application/json";
  170. int length = textData.length();
  171. String date = toGMTString(new Date());
  172. // 1.对body做MD5+BASE64加密
  173. String bodyMd5 = MD5Base64(textData.getBytes("UTF-8"));
  174. String stringToSign = method + "\n" + accept + "\n" + bodyMd5 + "\n" + content_type + "\n" + date ;
  175. // 2.计算 HMAC-SHA1
  176. String signature = HMACSha1(stringToSign, ak_secret);
  177. // 3.得到 authorization header
  178. String authHeader = "Dataplus " + ak_id + ":" + signature;
  179. // 打开和URL之间的连接
  180. HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
  181. // 设置通用的请求属性
  182. conn.setRequestProperty("accept", accept);
  183. conn.setRequestProperty("content-type", content_type);
  184. conn.setRequestProperty("date", date);
  185. conn.setRequestProperty("Authorization", authHeader);
  186. conn.setRequestProperty("Content-Length", String.valueOf(length));
  187. // 发送POST请求必须设置如下两行
  188. conn.setDoOutput(true);
  189. conn.setDoInput(true);
  190. // 获取URLConnection对象对应的输出流
  191. OutputStream stream = conn.getOutputStream();
  192. // 发送请求参数
  193. stream.write(textData.getBytes("UTF-8"));
  194. // flush输出流的缓冲
  195. stream.flush();
  196. stream.close();
  197. response.setStatus(conn.getResponseCode());
  198. // 定义BufferedReader输入流来读取URL的响应
  199. InputStream is = null;
  200. String line = null;
  201. if (response.getStatus() ==200){
  202. is=conn.getInputStream();
  203. }else {
  204. in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
  205. while ((line = in.readLine()) != null) {
  206. result += line;
  207. }
  208. }
  209. FileOutputStream fileOutputStream = null;
  210. File ttsFile = new File(audioName+"."+audioType);
  211. fileOutputStream = new FileOutputStream(ttsFile);
  212. byte[] b=new byte[1024];
  213. int len=0;
  214. while(is!=null&&(len=is.read(b))!=-1){ //先读到内存
  215. fileOutputStream.write(b, 0, len);
  216. }
  217. if (response.getStatus() == 200){
  218. response.setResult(result);
  219. response.setMassage("OK");
  220. System.out.println("post response status code: ["+response.getStatus()+"], generate tts audio file :" + audioName+"."+audioType);
  221. }else {
  222. response.setMassage(result);
  223. System.out.println("post response status code: ["+response.getStatus()+"], response massage : ["+response.getMassage()+"]");
  224. }
  225. } catch (Exception e) {
  226. System.out.println("发送 POST 请求出现异常!" + e);
  227. e.printStackTrace();
  228. }
  229. // 使用finally块来关闭输出流、输入流
  230. finally {
  231. try {
  232. if (out != null) {
  233. out.close();
  234. }
  235. if (in != null) {
  236. in.close();
  237. }
  238. } catch (IOException ex) {
  239. ex.printStackTrace();
  240. }
  241. }
  242. return response;
  243. }
  244. }

4.4 请求结果类

  1. package com.alibaba.idst.nls.response;
  2. public class HttpResponse {
  3. private int status;
  4. private String result;
  5. private String massage;
  6. public int getStatus() {
  7. return status;
  8. }
  9. public void setStatus(int status) {
  10. this.status = status;
  11. }
  12. public String getResult() {
  13. return result;
  14. }
  15. public void setResult(String result) {
  16. this.result = result;
  17. }
  18. public String getMassage() {
  19. return massage;
  20. }
  21. public void setMassage(String massage) {
  22. this.massage = massage;
  23. }
  24. }
本文导读目录
本文导读目录
以上内容是否对您有帮助?