SpringMVC调用讯飞语音合成WebApi示例

最近讯飞开放了语音合成的WebAPI,相对于之前SDK的方式方便了很多,下面使用SpringMVC写了一个示例,调用讯飞的合成API。

  • XFHelper.java
    负责调用讯飞WebAPI接口,处理HTTP头和参数,解析结果
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 nameValuePairArrayList = new ArrayList<>();
        nameValuePairArrayList.add(new BasicNameValuePair(key, body));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairArrayList, CHARSET));
    }
  • AIController.java
    负责对外提供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();
            // 如需直接播放音频,需添加对应的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);
        }
    }

你可能感兴趣的:(SpringMVC调用讯飞语音合成WebApi示例)