/** * Send input steam. * * @param inputStream the input stream * @throws IOException Signals that an I/O exception has occurred. */ private void sendInputSteam(InputStream inputStream) throws IOException { byte[] buffer = new byte[FOUR_KB]; int read; while ((read = inputStream.read(buffer)) > 0) { if (read == FOUR_KB) socket.sendMessage(RequestBody.create(WebSocket.BINARY, buffer)); else socket.sendMessage( RequestBody.create(WebSocket.BINARY, Arrays.copyOfRange(buffer, 0, read))); } inputStream.close(); }
/* * (non-Javadoc) * * @see okhttp3.ws.WebSocketListener#onOpen(okhttp3.ws.WebSocket, okhttp3.Response) */ @Override public void onOpen(WebSocket socket, Response response) { callback.onConnected(); this.socket = socket; try { socket.sendMessage( RequestBody.create(WebSocket.TEXT, buildStartMessage(options).toString())); } catch (IOException e) { callback.onError(e); } }
/* * (non-Javadoc) * * @see okhttp3.ws.WebSocketListener#onMessage(okhttp3.ResponseBody) */ @Override public void onMessage(ResponseBody response) throws IOException { String message = response.string(); if (message == null) return; try { JsonObject json = new JsonParser().parse(message).getAsJsonObject(); if (json.has(ERROR)) { callback.onError(new RuntimeException(json.get(ERROR).getAsString())); } else if (json.has(RESULTS)) { callback.onTranscription(GSON.fromJson(message, SpeechResults.class)); } else if (json.has(STATE)) { if (!audioSent) { sendInputSteam(stream); socket.sendMessage(RequestBody.create(WebSocket.TEXT, buildStopMessage().toString())); audioSent = true; } else { socket.close(CLOSE_NORMAL, "Transcription completed"); } } } catch (JsonParseException e) { throw new RuntimeException("Error parsing the incoming message: " + response.string()); } }