springboot项目集成科大讯飞文字转语音
首先到https://console.xfyun.cn/注册实名认证,得到相应的密钥
根据api文档我们了解到这个调用过程
在项目中集成
首先引入需要的依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.5.3</version>
</dependency>
在yml文件中配置相应参数
xunfei:
hostUrl: http://tts-api.xfyun.cn/v2/tts
appid:
apisecret:
apikey:
现在写一个工具类
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import okhttp3.*;
import okio.ByteString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
//静态参数注入,必须增加@Component注解
@Component
public class XunFeiUtil {
protected static final Logger log = LoggerFactory.getLogger(XunFeiUtil.class);
//讯飞四个注入参数,保存在配置文件,便于复用和避免代码上传gitee后泄漏
private static String hostUrl;
@Value("${xunfei.hostUrl}")
public void setHostUrl(String hostUrl) {
XunFeiUtil.hostUrl = hostUrl;
}
private static String appid;
@Value("${xunfei.appid}")
public void setAppid(String appid) {
XunFeiUtil.appid = appid;
}
private static String apiSecret;
@Value("${xunfei.apisecret}")
public void setApiSecret(String apiSecret) {
XunFeiUtil.apiSecret = apiSecret;
}
private static String apiKey;
@Value("${xunfei.apikey}")
public void setApiKey(String apiKey) {
XunFeiUtil.apiKey = apiKey;
}
public static final Gson json = new Gson();
private static String base64 = "";
private static volatile boolean lock = true;
/**
* 将文本转换为MP3格语音base64文件
*
* @param text 要转换的文本(如JSON串)
* @return 转换后的base64文件
*
*/
public static String convertText(String text) throws Exception {
lock = true;
base64 = "";
// 构建鉴权url
String authUrl = getAuthUrl(hostUrl, apiKey, apiSecret);
OkHttpClient client = new OkHttpClient.Builder().build();
//将url中的 schema http://和https://分别替换为ws:// 和 wss://
String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
Request request = new Request.Builder().url(url).build();
List<byte[]> list = Lists.newArrayList();