This commit is contained in:
2025-09-23 10:54:46 +08:00
parent e08cbe45d4
commit c23fc9f9f5
31 changed files with 661 additions and 477 deletions

View File

@@ -17,9 +17,9 @@ public class SpeechRecognitionWebSocketHandler {
public SpeechRecognitionWebSocketHandler() {
// 初始化语音识别器
String appKey = "LuvNcrddU3PH8Tau";
String id = "LTAI5tRBahK93vPNF1JDVEPA";
String secret = "x95OWb4cV6ccQVtbEJ2Gxm2Uwl2thJ";
String appKey = "4lFYn2yPsQymwGu8";
String id = "LTAI5t9hhSqdDHqwH3RjgyYj";
String secret = "ni5aW3vxrWouMwcGqJPfh9Uu56PBuv";
String url = System.getenv().getOrDefault("NLS_GATEWAY_URL", "wss://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1");
recognizerDemo = new SpeechRecognizerAI(appKey, id, secret, url);
}
@@ -44,6 +44,7 @@ public class SpeechRecognitionWebSocketHandler {
recognizerDemo.processStream(session, new ByteArrayInputStream(audioData), 16000);
}
/**
* 连接关闭调用的方法
*/

View File

@@ -7,23 +7,24 @@ import com.alibaba.nls.client.protocol.SampleRateEnum;
import com.alibaba.nls.client.protocol.asr.SpeechRecognizer;
import com.alibaba.nls.client.protocol.asr.SpeechRecognizerListener;
import com.alibaba.nls.client.protocol.asr.SpeechRecognizerResponse;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.websocket.Session;
import java.io.IOException;
import java.io.InputStream;
@Data
public class SpeechRecognizerAI {
private static final Logger logger = LoggerFactory.getLogger(SpeechRecognizerAI.class);
private String appKey;
private NlsClient client;
private AccessToken accessToken;
public SpeechRecognizerAI(String appKey, String id, String secret, String url) {
this.appKey = appKey;
// 获取 AccessToken
AccessToken accessToken = new AccessToken(id, secret);
accessToken = new AccessToken(id, secret);
try {
accessToken.apply(); // 申请 Token
logger.info("Token: {}, Expire Time: {}", accessToken.getToken(), accessToken.getExpireTime());
@@ -114,4 +115,28 @@ public class SpeechRecognizerAI {
client.shutdown();
}
}
/**
* 获取当前有效的 AccessToken
*
* @param id 阿里云 AccessKey ID
* @param secret 阿里云 AccessKey Secret
* @return 返回申请到的 AccessToken 字符串,失败时返回 null
*/
public static String getAccessToken(String id, String secret) {
try {
AccessToken accessToken = new AccessToken(id, secret);
accessToken.apply(); // 申请 token
if (accessToken.getToken() != null) {
logger.info("成功获取 Token: {}, 过期时间: {}", accessToken.getToken(), accessToken.getExpireTime());
return accessToken.getToken();
} else {
logger.error("get token fail:"+accessToken.getToken());
return null;
}
} catch (IOException e) {
logger.error("申请 Token 时发生网络错误: {}", e.getMessage());
return null;
}
}
}