IFlyUtils.java
6.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package com.bsth.util;
import com.bsth.entity.speech.SpeechRequest;
import com.bsth.entity.speech.SpeechResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
public class IFlyUtils {
private final static ObjectMapper mapper = new ObjectMapper();
private final static Logger log = LoggerFactory.getLogger(IFlyUtils.class);
private final static String apiKey = "46780e6779b6b1ba93503f24f097b771";
private final static String apiSecret = "ZWFjNzkzMTkzNzI3YmMzMTgwMWUzMWE0";
private final static String appId = "b4b21ad4";
private static Map<String, String> language2vcn = new HashMap<>();
static {
language2vcn.put("cn", "x4_lingxiaoshan_profnews");
language2vcn.put("sh", "x3_ziling");
language2vcn.put("en", "x4_enus_luna_assist");
}
public static void textToSpeech(String text, String language, String outputPath) throws Exception {
File file = new File(outputPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
String vcn = language2vcn.get(language);
if (vcn == null) {
throw new IllegalArgumentException("Language is not supported: " + language);
}
String wsUrl = getAuthUrl("https://tts-api.xfyun.cn/v2/tts", apiKey, apiSecret).replace("https://", "wss://");
SpeechRequest request = new SpeechRequest();
request.getCommon().put("app_id", appId);
request.getBusiness().put("aue", "lame");
request.getBusiness().put("sfl", 1);
request.getBusiness().put("vcn", vcn);
String charset = "GBK";
if ("en".equals(language)) {
charset = "UTF-8";
}
if ("en".equals(language) || "sh".equals(language)) {
request.getBusiness().put("volume", 100);
}
request.getData().put("text", Base64.getEncoder().encodeToString(text.replace(",", "[p1000]").getBytes(charset)));
request.getData().put("status", 2);
websocketWork(wsUrl, request, new FileOutputStream(file));
while (!request.isCompleted()) {
Thread.sleep(500);
}
}
public static void websocketWork(String wsUrl, SpeechRequest request, OutputStream out) {
try {
URI uri = new URI(wsUrl);
WebSocketClient webSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
try {
this.send(mapper.writeValueAsString(request));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
@Override
public void onMessage(String text) {
try {
SpeechResponse response = mapper.readValue(text, SpeechResponse.class);
log.info("response: {}", response);
if (response.getCode() != 0) {
log.error("在线语音合成发生错误");
}
if (response.getData() != null) {
byte[] bytes = Base64.getDecoder().decode(response.getData().getAudio());
out.write(bytes);
out.flush();
if (response.getData().getStatus() == 2) {
request.setCompleted(true);
out.close();
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void onClose(int i, String s, boolean b) {
System.out.println("ws链接已关闭,本次请求完成...");
}
@Override
public void onError(Exception e) {
log.error("发生错误", e);
}
};
webSocketClient.connect();
} catch (Exception e) {
log.error("", e);
}
}
/**
* 讯飞语音合成鉴权
* @param hostUrl
* @param apiKey
* @param apiSecret
* @return
* @throws Exception
*/
public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
URL url = new URL(hostUrl);
// 时间
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
String date = format.format(new Date());
// 拼接
String preStr = "host: " + url.getHost() + "\n" +
"date: " + date + "\n" +
"GET " + url.getPath() + " HTTP/1.1";
// SHA256加密
Mac mac = Mac.getInstance("hmacsha256");
SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
mac.init(spec);
byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
// Base64加密
String sha = Base64.getEncoder().encodeToString(hexDigits);
// 拼接
String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
StringBuilder sb = new StringBuilder(hostUrl);
sb.append("?authorization=").append(Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8)))
.append("&date=").append(URLEncoder.encode(date))
.append("&host=").append(URLEncoder.encode(url.getHost()));
// // 拼接地址
// HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
// addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
// addQueryParameter("date", date).//
// addQueryParameter("host", url.getHost()).//
// build();
return sb.toString();
}
}