TTS 返回语音优化

This commit is contained in:
2025-10-19 17:01:13 +08:00
parent a75d2dd985
commit a3ef5d1959
3 changed files with 26 additions and 45 deletions

View File

@@ -169,6 +169,7 @@
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-websocket</artifactId>

View File

@@ -1,5 +1,6 @@
package com.vetti.common.ai.gpt;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.vetti.common.ai.gpt.service.OpenAiStreamListenerService;
@@ -9,7 +10,9 @@ import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
@@ -30,6 +33,12 @@ public class OpenAiStreamClient {
@Value("${chatGpt.role}")
private String role;
// 定义作为分割点的标点符号集合
private final Set<Character> punctuationSet = new HashSet<>() {{
add('。'); add(''); add(''); add(''); // 中文标点
add('.'); add('?'); add('!'); add(';'); // 英文标点
}};
/**
* 发送流式请求
*
@@ -42,6 +51,9 @@ public class OpenAiStreamClient {
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build();
// 文本缓冲区
StringBuffer bufferStr = new StringBuffer();
// 构建请求参数
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("model", model);
@@ -104,7 +116,19 @@ public class OpenAiStreamClient {
.getStr("content");
if (content != null && !content.isEmpty()) {
listener.onMessage(content);
if(punctuationSet.contains(content)){
//说明有标点啦,直接返回
bufferStr.append(content);
listener.onMessage(bufferStr.toString());
}else{
//加入缓冲区
if(StrUtil.isEmpty(bufferStr.toString())){
bufferStr.append(content);
}else {
bufferStr.append(" ").append(content);
}
}
}
} catch (Exception e) {
listener.onError(new IOException("Parse error: " + e.getMessage()));