【发布时间】:2017-02-26 15:44:47
【问题描述】:
我正在构建一个 Unity3D 应该与之通信的 Sphinx4 Java 服务器。将音频数据从 Unity C# 发送到 Java 服务器工作正常。使用接收到的数据进行语音识别也可以正常工作。当我尝试将数据从 Java 发送回 C# 时出现问题。
我当前的代码: JAVA
package main;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.SpeechResult;
import edu.cmu.sphinx.api.StreamSpeechRecognizer;
public class SpeechRecognition {
private static StreamSpeechRecognizer recognizer;
private static Configuration configuration;
public static void main(String[] args) {
configuration = new Configuration();
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.bin");
try {
recognizer = new StreamSpeechRecognizer(configuration);
ServerSocket serverSocket = new ServerSocket(82);
while (System.in.available() == 0) {
Socket socket = serverSocket.accept();
System.out.println("Client found");
String recognized = RecognizeText(socket.getInputStream());
System.out.println("sending now");
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String json = recognized;
out.print(json);
out.flush();
out.close();
socket.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Quitting...");
serverSocket.close();
}
private static String RecognizeText(InputStream stream) throws Exception {
recognizer.startRecognition(stream);
SpeechResult result;
String resultString="";
while ((result = recognizer.getResult()) != null) {
resultString = result.getHypothesis();
System.out.format("Hypothesis: %s\n", resultString);
}
recognizer.stopRecognition();
return resultString;
}
}
现在我的 C# 代码是这样的:
void Start () {
dataPath = Application.dataPath;
t = new Thread(Client);
t.Start();
}
private void Client()
{
String input;
TcpClient tcpClient = new TcpClient("localhost", 82);
NetworkStream networkStream = tcpClient.GetStream();
BinaryWriter bw = new BinaryWriter(networkStream);
var filepath = dataPath + "/Resources/audio/test.wav";
FileStream filestream = new FileStream(filepath, FileMode.Open, FileAccess.Read);
BinaryReader filereader = new BinaryReader(filestream);
byte[] bytes = filereader.ReadBytes((Int32)filestream.Length);
bw.Write(bytes);
bw.Flush();
StreamReader streamReader = new StreamReader(networkStream);
input = streamReader.ReadToEnd();
print("Received data: " + input + "\n");
}
识别大约需要 10 秒。当给出结果时,系统冻结。 不打印 Println("sending now")(在 Java 中)。所以它甚至在到达它之前就冻结了。
奇怪的是:当我只将文本从 Java 发送到 C# 或从 C# 发送到 Java 时,它可以工作。如果我想在两端发送和接收,它会冻结。而且我需要同时发送和接收数据
【问题讨论】:
标签: java c# unity3d server tcpclient