最近訊飛開放了語音合成的WebAPI牺氨,相對于之前SDK的方式方便了很多孔轴,下面使用SpringMVC寫了一個示例筋现,調(diào)用訊飛的合成API矾睦。
- XFHelper.java
負(fù)責(zé)調(diào)用訊飛WebAPI接口掉奄,處理HTTP頭和參數(shù)规个,解析結(jié)果
public class XFAiHelper {
private static final String APP_ID = "你的APP_ID";
private static final String TTS_APP_KEY = "你的APP_KEY";
private static final String API_DOMAIN = "http://api.xfyun.cn";
private static final String TTS_PATH = "/v1/service/v1/tts";
private static final byte[] TTS_PARAM = "{\"auf\":\"audio/L16;rate=16000\",\"aue\":\"lame\",\"voice_name\":\"xiaoyan\",\"engine_type\":\"aisound\"}".getBytes();
private static final String CHARSET = "UTF-8";
public static byte[] tts(String text) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(API_DOMAIN + TTS_PATH);
addFormData(httpPost, "text", text);
String param = Base64.getEncoder().encodeToString(TTS_PARAM);
addAiHeader(httpPost, param, TTS_APP_KEY);
CloseableHttpResponse httpResponse = httpclient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200
&& StringUtils.equals(httpResponse.getFirstHeader("Content-Type").getValue(), "audio/mpeg")) {
InputStream inputStream = httpResponse.getEntity().getContent();
return IOUtils.toByteArray(inputStream);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
private static void addAiHeader(HttpPost httpPost, String param, String appKey, String key, String body) {
httpPost.setHeader("X-Appid", APP_ID);
httpPost.setHeader("X-Param", param);
String curTime = String.valueOf(System.currentTimeMillis() / 1000);
httpPost.setHeader("X-CurTime", curTime);
String checkStr = appKey + curTime + param;
String checkSum = new Md5PasswordEncoder().encodePassword(checkStr, null);
httpPost.setHeader("X-CheckSum", checkSum);
}
private static void addFormData(HttpPost httpPost, String key, String body) throws UnsupportedEncodingException {
List<NameValuePair> nameValuePairArrayList = new ArrayList<>();
nameValuePairArrayList.add(new BasicNameValuePair(key, body));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairArrayList, CHARSET));
}
- AIController.java
負(fù)責(zé)對外提供Web接口
@RequestMapping("/tts")
public ResponseEntity tts(String text, HttpServletResponse response) throws IOException {
byte[] audio = XFAiHelper.tts(text);
if (audio != null && audio.length > 0) {
final HttpHeaders headers = new HttpHeaders();
// 如需直接播放音頻,需添加對應(yīng)的ContentType和ContentLength
headers.setContentType(new MediaType("audio", "mpeg"));
headers.setContentLength(audio.length);
// 如需下載音頻姓建,添加如下header
// headers.setContentDispositionFormData("attchement", fileName);
return new ResponseEntity<>(audio, headers, HttpStatus.OK);
} else {
return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
}
}