forked from dyf/fys-Multi-tenant
85 lines
3.2 KiB
Java
85 lines
3.2 KiB
Java
package com.fuyuanshen.app.http;
|
||
|
||
import org.apache.http.HttpEntity;
|
||
import org.apache.http.HttpResponse;
|
||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||
import org.apache.http.client.methods.HttpPost;
|
||
import org.apache.http.entity.StringEntity;
|
||
import org.apache.http.impl.client.CloseableHttpClient;
|
||
import org.apache.http.impl.client.HttpClients;
|
||
import org.apache.http.util.EntityUtils;
|
||
import java.io.FileOutputStream;
|
||
import java.io.IOException;
|
||
import java.util.Base64;
|
||
|
||
public class ApacheHttpTtsClient {
|
||
|
||
private String accessKeyId;
|
||
private String accessKeySecret;
|
||
private String appKey;
|
||
|
||
public ApacheHttpTtsClient(String accessKeyId, String accessKeySecret, String appKey) {
|
||
this.accessKeyId = accessKeyId;
|
||
this.accessKeySecret = accessKeySecret;
|
||
this.appKey = appKey;
|
||
}
|
||
|
||
/**
|
||
* 使用Apache HttpClient调用TTS服务
|
||
*/
|
||
public byte[] synthesizeTextToMp3(String text) throws IOException {
|
||
CloseableHttpClient httpClient = HttpClients.createDefault();
|
||
|
||
try {
|
||
HttpPost httpPost = new HttpPost("https://nls-gateway.cn-shanghai.aliyuncs.com/v1/tts");
|
||
|
||
// 设置请求头
|
||
httpPost.setHeader("Content-Type", "application/json");
|
||
httpPost.setHeader("Authorization", "Bearer " + getAccessToken());
|
||
|
||
// 设置请求体
|
||
String jsonPayload = String.format(
|
||
"{\"appkey\":\"%s\",\"text\":\"%s\",\"voice\":\"zhifeng\",\"format\":\"MP3\",\"sample_rate\":24000,\"volume\":50,\"speech_rate\":0,\"pitch_rate\":0}",
|
||
appKey,
|
||
text.replace("\"", "\\\"")
|
||
);
|
||
|
||
StringEntity entity = new StringEntity(jsonPayload, "UTF-8");
|
||
httpPost.setEntity(entity);
|
||
|
||
// 执行请求
|
||
CloseableHttpResponse response = httpClient.execute(httpPost);
|
||
try {
|
||
HttpEntity responseEntity = response.getEntity();
|
||
if (response.getStatusLine().getStatusCode() == 200) {
|
||
// 读取响应数据(Base64编码的音频数据)
|
||
String responseStr = EntityUtils.toString(responseEntity);
|
||
|
||
// 如果返回的是Base64编码的数据
|
||
if (responseStr.startsWith("data:audio/mp3;base64,")) {
|
||
String base64Data = responseStr.substring("data:audio/mp3;base64,".length());
|
||
return Base64.getDecoder().decode(base64Data);
|
||
} else {
|
||
// 直接返回音频数据
|
||
return EntityUtils.toByteArray(responseEntity);
|
||
}
|
||
} else {
|
||
throw new IOException("请求失败: " + response.getStatusLine().getStatusCode());
|
||
}
|
||
} finally {
|
||
response.close();
|
||
}
|
||
} finally {
|
||
httpClient.close();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取访问令牌
|
||
*/
|
||
private String getAccessToken() {
|
||
// 实现获取阿里云访问令牌的逻辑
|
||
return "your-access-token";
|
||
}
|
||
}
|