如何使用 Java 和 Spring 开发允许与用户进行音频聊天的 Web 应用程序?我在 Java Web 7 ([ https://tyrus.java.net/][Project Tyrus]) 中使用了 WebSocket,它非常适用于文本按摩。
但是对于音频聊天,我无法弄清楚。我尝试使用 WebRTC 来检测麦克风,这是客户端代码:
var ws2 = "ws://localhost:8080/WindTest/voiceChat/asd/username";
var websocket = new WebSocket(ws2);
var session = {
audio: true,
video: false
};
function initializeRecorder(stream) {
var audioContext = window.AudioContext;
var context = new audioContext();
var audioInput = context.createMediaStreamSource(stream);
var bufferSize = 2048;
// create a javascript node
//var recorder = context.createJavaScriptNode(bufferSize, 1, 1);
var recorder = context.createScriptProcessor(bufferSize, 1, 1);
// specify the processing function
recorder.onaudioprocess = sendAudio;
// connect stream to our recorder
audioInput.connect(recorder);
// connect our recorder to the previous destination
recorder.connect(context.destination);
}
function onError(error){
console.log(error);
}
navigator.getUserMedia(session, initializeRecorder, onError);
function sendAudio(e) {
var left = e.inputBuffer.getChannelData(0);
//Send audio over websocket
websocket.send(msg);
}
服务器端:
@ServerEndpoint(value = "/voiceChat/{room}/{username}")
public class VoiceChatEndPoint {
@OnMessage
public void broadcastMsg(Object object, Session session) {
boolean roomExist = false;
for (Session peer : session.getOpenSessions()) {
try {
peer.getBasicRemote().sendObject(object);
// roomExist = true;
} catch (IOException ex) {
Logger.getLogger(VoiceChatEndPoint.class.getName()).log(Level.SEVERE, null, ex);
} catch (EncodeException ex) {
Logger.getLogger(VoiceChatEndPoint.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
我有一个例外,我认为这是关于解码和编码,但我不知道如何处理它:
Info: Unhandled exception in endpoint com.wind.ptt.VoiceChatEndPoint.
java.lang.IllegalStateException: Text message handler not found. Session: 'TyrusSession{uri=/WindTest/voiceChat/asd/username, id='6899d950-9e2e-4950-8bb8-03bd839253c0', endpointWrapper=TyrusEndpointWrapper{endpointClass=null, endpoint=org.glassfish.tyrus.core.AnnotatedEndpoint@5bb273b4, contextPath='/WindTest'}}'.
at org.glassfish.tyrus.core.TyrusEndpointWrapper.onMessage(TyrusEndpointWrapper.java:752)
at org.glassfish.tyrus.core.TyrusWebSocket.onMessage(TyrusWebSocket.java:200)
at org.glassfish.tyrus.core.frame.TextFrame.respond(TextFrame.java:135)
at org.glassfish.tyrus.core.ProtocolHandler.process(ProtocolHandler.java:622)
at org.glassfish.tyrus.core.TyrusWebSocketEngine$TyrusReadHandler.handle(TyrusWebSocketEngine.java:394)
at org.glassfish.tyrus.servlet.TyrusHttpUpgradeHandler.onDataAvailable(TyrusHttpUpgradeHandler.java:164)
at org.apache.catalina.connector.InputBuffer$ReadHandlerImpl.processDataAvailable(InputBuffer.java:488)
如何使用 Java(Tyrus 项目、websocket、Spring)进行音频聊天提前谢谢