java Java片段
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Java片段相关的知识,希望对你有一定的参考价值。
/**
* File from MP3 to WAV
*/
File file = new File(fileName);
AudioInputStream in= AudioSystem.getAudioInputStream(file);
AudioInputStream din = null;
AudioFormat baseFormat = in.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
16000, 16, 1, 2,baseFormat.getSampleRate(), false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
File file_wav = new File("/var/www/my_folder");
AudioSystem.write(din, Type.WAVE, file_wav);
@WebServlet("/orchestrator")
public class orchestrator extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final HashMap<Integer, String> FILA = new HashMap<Integer, String>();
public orchestrator() {
super();
//init FILA
if(FILA.size()==0) {
for (int i = 0; i>500 ; i++) {
Integer key = i;
String value = null;
FILA.put(key, value);
}
}
}
protected static void releasePort(Integer key) {
FILA.put(key,null);
}
protected static String getCallId(Integer key) {
return FILA.get(key);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NoClassDefFoundError {
String codigo = request.getParameter("cod");
if(codigo==null) {
response.getWriter().append("campo COD esta vazio");
return;
}
Integer[] portas = new Integer[4];
for (int i = 0; i<500; i++) {
if (FILA.get(i) == null ) {
FILA.put(i, codigo);
/*
* porta_agente = 9000 + idporta
* porta_cliente = 9500 + idporta
*/
portas[i] = 9000+i;
System.out.println(portas[i]);
SocketListener.main(portas[i]);
//SocketListener.instance(500+i);
break;
}
}
response.addHeader("Content-type", "application/json");
response.getWriter().append(portas.toString());
}
}
public class SocketListener {
public static void main(final int port) {
new Thread(new Runnable() {
@Override
public void run() {
try {
String callId = orchestrator.getCallId(key>=500?key-500:key);
ServerSocket srv = new ServerSocket(port);
srv.setSoTimeout(30000);
System.out.println("aguardando..."+srv.getLocalPort());
Socket cli = srv.accept();
cli.setSoTimeout(6000);
System.out.println("aceito.."+srv.getLocalPort());
InputStream is = cli.getInputStream();
OutputStream os = cli.getOutputStream();
Stream ds = new Stream();
ds.speechStreamingGoogle(srv,is,os);
orchestrator.releasePort(key);
}catch (Throwable e) {
e.printStackTrace();
}
}
}).start();
}
}
/**
* Calculates the similarity (a number within 0 and 1) between two strings.
*/
public static double similarity(String s1, String s2) {
String longer = s1, shorter = s2;
if (s1.length() < s2.length()) { // longer should always have greater length
longer = s2; shorter = s1;
}
try {
int longerLength = longer.length();
if (longerLength == 0) { return 1.0; /* both strings are zero length */ }
LevenshteinDistance levenshteinDistance = new LevenshteinDistance();
return (longerLength - levenshteinDistance.apply(longer, shorter)) / (double) longerLength;
}catch(Exception e) {
e.printStackTrace();
}
return new Double(1000);
}
public void detectSilenceFromStream(final ServerSocket srv, final InputStream is, final OutputStream os)
throws IOException, UnsupportedAudioFileException {
Runnable runner = new Runnable() {
int bufferSize = (int) format.getSampleRate() * format.getFrameSize();
byte buffer[] = new byte[bufferSize];
boolean isSilence = true;
public void run() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
/*
* Contador acumulativo para reconstru��o do chat
*/
int countAc = 0;
int count = 0;
try {
try {
while ((count = is.read(buffer, 0, buffer.length)) > -1) {
try {
countAc += count;
File temp = null;
String seq = null;
float level = calculateLevel(buffer, 0, 0);
/*
* Iniciou a fala, come�a a grava��o
*/
if (isSilence && level >= 0.2) {
out = new ByteArrayOutputStream();
isSilence = false;
}
if (!isSilence) {
seq = "000000000000" + countAc;
temp = new File("/tmp/audio/" + seq.substring(seq.length() - 12) + "_" + channel
+ "_" + callId + ".wav");
try {
temp.getParentFile().mkdirs();
} catch (Exception e) {
}
}
/*
* Level muito baixo indica que a pessoa parou de falar Pega o arquivo, para de
* gravar
*/
if (level <= 0.04 && !isSilence && temp != null && seq != null) {
String resp = getAudioFile(temp, out, seq);
if (resp != null) {
os.write((resp + "\n").getBytes());
os.flush();
}
isSilence = true;
} else {
// System.out.print(".");
}
/*
* mesmo silencio (ou fone mutado) o count d� maior que 0 s� cai no else quando
* encerra a liga��o mesmo
*/
out.write(buffer, 0, count);
} catch (Exception e) {
e.printStackTrace();
}
} // while
} catch (SocketTimeoutException e) {
System.out.println("socket-timeout");
} catch (Exception e) {
e.printStackTrace();
}
os.close();
System.out.println("Encerrando " + srv.getLocalPort());
srv.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
Thread captureThread = new Thread(runner);
captureThread.start();
}
/**
* Execute shell commands
* @param List First the command, then arguments
* @param boolean If we want a response
* @return
*/
public static String executeCommand(List<String> params, boolean waitForResponse) {
String response = "";
ProcessBuilder pb = new ProcessBuilder(params);
pb.redirectErrorStream(true);
pb.directory(new File("C://var//www//SpeechRecognitionService"));
try {
Process shell = pb.start();
if (waitForResponse) {
// To capture output from the shell
InputStream shellIn = shell.getInputStream();
// Wait for the shell to finish and get the return code
int shellExitStatus = shell.waitFor();
if (shellExitStatus > 0) {
System.out.println("Exit status " + shellExitStatus);
//setClosed(false);
response = "";
} else {
response = convertStreamToStr(shellIn);
//System.out.println(response);
}
shellIn.close();
}
} catch (IOException e) {
System.out.println("Error occured while executing Linux command. Error Description: "
+ e.getMessage());
} catch (InterruptedException e) {
System.out.println("Error occured while executing Linux command. Error Description: "
+ e.getMessage());
}
return response;
}
// Chamando
params = Arrays.asList("cmd.exe", "msys.bat -norxvt", "go.sh");
executeCommand(params, true);
final Socket cli = new Socket("localhost", port);
final FileInputStream fis = new FileInputStream(new File(path));
final byte[] buffer = new byte[BUFFER_SIZE];
new Thread(new Runnable() {
public void run() {
int read = 0;
try {
while ( (read = fis.read(buffer)) > 0) {
cli.getOutputStream().write(buffer);
}
fis.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(cli.getInputStream(), StandardCharsets.US_ASCII));
while (!br.ready()) Thread.sleep(400);
while((line = br.readLine())!=null && !line.trim().isEmpty()) {
// read line by line
}
cli.close();
}
}).start();
/**
* Connect to RESTful API
*/
RestClient cli = new RestClient(url) {
@Override
public void whenDone(Response resp) {
try{
JSONObject json = new JSONObject(new JSONTokener(resp.getContent()));
String file_wav_path = convertMp3toWav(fileName+".mp3");
connectWebSocket(file_wav_path, 9000); //snippet ClientWebSocket
}catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Não foi possível conectar com o servidor!");
}
}
};
cli.doGet();
以上是关于java Java片段的主要内容,如果未能解决你的问题,请参考以下文章