|
| 1 | +package oracleai; |
| 2 | + |
| 3 | +import com.google.api.gax.rpc.ApiStreamObserver; |
| 4 | +import com.google.api.gax.rpc.BidiStreamingCallable; |
| 5 | +import com.google.cloud.speech.v1.*; |
| 6 | +import com.google.protobuf.ByteString; |
| 7 | +import org.springframework.stereotype.Component; |
| 8 | +import org.springframework.web.socket.BinaryMessage; |
| 9 | +import org.springframework.web.socket.CloseStatus; |
| 10 | +import org.springframework.web.socket.WebSocketSession; |
| 11 | +import org.springframework.web.socket.handler.BinaryWebSocketHandler; |
| 12 | +import org.springframework.web.socket.TextMessage; |
| 13 | + |
| 14 | +import java.io.FileOutputStream; |
| 15 | +import java.io.IOException; |
| 16 | +import java.nio.ByteBuffer; |
| 17 | +import java.nio.file.Files; |
| 18 | +import java.nio.file.Paths; |
| 19 | +import java.util.Arrays; |
| 20 | +import java.util.concurrent.ConcurrentHashMap; |
| 21 | + |
| 22 | +@Component |
| 23 | +public class CustomWebSocketHandler extends BinaryWebSocketHandler { |
| 24 | + private static final ConcurrentHashMap<String, ApiStreamObserver<StreamingRecognizeRequest>> activeSessions = new ConcurrentHashMap<>(); |
| 25 | + private static SpeechClient speechClient; |
| 26 | + private static final int MIN_AUDIO_BUFFER_SIZE = 48000; // 🔥 Buffer at least 3 seconds before sending |
| 27 | + private static final double SILENCE_THRESHOLD = 0.01; // 🔥 Adjust silence detection (RMS method) |
| 28 | + |
| 29 | + static { |
| 30 | + try { |
| 31 | + speechClient = SpeechClient.create(); |
| 32 | + } catch (IOException e) { |
| 33 | + throw new RuntimeException("Failed to initialize SpeechClient", e); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + @Override |
| 38 | + public void afterConnectionEstablished(WebSocketSession session) { |
| 39 | + System.out.println("✅ WebSocket Connected: " + session.getId()); |
| 40 | + |
| 41 | + ApiStreamObserver<StreamingRecognizeResponse> responseObserver = new ApiStreamObserver<>() { |
| 42 | + @Override |
| 43 | + public void onNext(StreamingRecognizeResponse response) { |
| 44 | + for (StreamingRecognitionResult result : response.getResultsList()) { |
| 45 | + if (result.getAlternativesCount() > 0) { |
| 46 | + String transcript = result.getAlternatives(0).getTranscript().trim(); |
| 47 | + if (!transcript.isEmpty()) { |
| 48 | + System.out.println("📝 Full API Response: " + response.toString()); |
| 49 | + System.out.println("📝 Transcription: " + transcript); |
| 50 | + |
| 51 | + try { |
| 52 | + session.sendMessage(new TextMessage(transcript)); |
| 53 | + } catch (IOException e) { |
| 54 | + e.printStackTrace(); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + @Override |
| 62 | + public void onError(Throwable t) { |
| 63 | + System.err.println("❌ Google API Error: " + t.getMessage()); |
| 64 | + } |
| 65 | + |
| 66 | + @Override |
| 67 | + public void onCompleted() { |
| 68 | + System.out.println("✅ Streaming completed."); |
| 69 | + } |
| 70 | + }; |
| 71 | + |
| 72 | + // ✅ Configure Google Speech API for better accuracy |
| 73 | + BidiStreamingCallable<StreamingRecognizeRequest, StreamingRecognizeResponse> callable = |
| 74 | + speechClient.streamingRecognizeCallable(); |
| 75 | + ApiStreamObserver<StreamingRecognizeRequest> requestObserver = callable.bidiStreamingCall(responseObserver); |
| 76 | + activeSessions.put(session.getId(), requestObserver); |
| 77 | + |
| 78 | + RecognitionConfig config = RecognitionConfig.newBuilder() |
| 79 | + .setEncoding(RecognitionConfig.AudioEncoding.LINEAR16) |
| 80 | + .setSampleRateHertz(16000) |
| 81 | + .setLanguageCode("en-US") |
| 82 | + .setEnableAutomaticPunctuation(true) |
| 83 | + .setModel("latest_long") // ✅ Best for longer speech |
| 84 | + .setAudioChannelCount(1) |
| 85 | + .setEnableWordTimeOffsets(true) |
| 86 | + .build(); |
| 87 | + |
| 88 | + StreamingRecognitionConfig streamingConfig = StreamingRecognitionConfig.newBuilder() |
| 89 | + .setConfig(config) |
| 90 | + .setInterimResults(true) |
| 91 | + .setSingleUtterance(false) // ✅ Allows continuous speech |
| 92 | + .build(); |
| 93 | + |
| 94 | + requestObserver.onNext(StreamingRecognizeRequest.newBuilder() |
| 95 | + .setStreamingConfig(streamingConfig) |
| 96 | + .build()); |
| 97 | + } |
| 98 | + |
| 99 | + @Override |
| 100 | + protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) { |
| 101 | + ByteBuffer payload = message.getPayload(); |
| 102 | + byte[] audioBytes = new byte[payload.remaining()]; |
| 103 | + payload.get(audioBytes); |
| 104 | + |
| 105 | + // ✅ Verify PCM Format |
| 106 | + if (!isValidPCMFormat(audioBytes)) { |
| 107 | + System.out.println("⚠️ Invalid PCM format. Skipping..."); |
| 108 | + return; |
| 109 | + } |
| 110 | + |
| 111 | + // ✅ Check silence with RMS (Root Mean Square) |
| 112 | + if (isSilent(audioBytes)) { |
| 113 | + System.out.println("🔇 Skipping silent audio."); |
| 114 | + return; |
| 115 | + } |
| 116 | + |
| 117 | + // ✅ Save to WAV file |
| 118 | + try { |
| 119 | + saveAudioToWAV(audioBytes, "audio_" + System.currentTimeMillis() + ".wav"); |
| 120 | + } catch (IOException e) { |
| 121 | + e.printStackTrace(); |
| 122 | + } |
| 123 | + |
| 124 | + // ✅ Buffering audio before sending |
| 125 | + if (audioBytes.length < MIN_AUDIO_BUFFER_SIZE) { |
| 126 | + System.out.println("⏳ Accumulating audio, not sending yet..."); |
| 127 | + return; // Don't send yet, wait for more audio |
| 128 | + } |
| 129 | + |
| 130 | + // ✅ Send to Google API |
| 131 | + if (activeSessions.containsKey(session.getId())) { |
| 132 | + ApiStreamObserver<StreamingRecognizeRequest> requestObserver = activeSessions.get(session.getId()); |
| 133 | + requestObserver.onNext(StreamingRecognizeRequest.newBuilder() |
| 134 | + .setAudioContent(ByteString.copyFrom(audioBytes)) |
| 135 | + .build()); |
| 136 | + } |
| 137 | + } |
| 138 | + |
| 139 | + // ✅ Validate PCM Format |
| 140 | + private boolean isValidPCMFormat(byte[] audioData) { |
| 141 | + if (audioData.length < 2) return false; |
| 142 | + |
| 143 | + for (int i = 0; i < audioData.length; i += 2) { |
| 144 | + short sample = (short) ((audioData[i + 1] << 8) | (audioData[i] & 0xFF)); |
| 145 | + if (sample < -32768 || sample > 32767) { |
| 146 | + return false; // Not valid 16-bit PCM range |
| 147 | + } |
| 148 | + } |
| 149 | + return true; |
| 150 | + } |
| 151 | + |
| 152 | + // ✅ Improved Silence Detection with RMS |
| 153 | + private boolean isSilent(byte[] audioData) { |
| 154 | + double sum = 0.0; |
| 155 | + for (int i = 0; i < audioData.length; i += 2) { |
| 156 | + short sample = (short) ((audioData[i + 1] << 8) | (audioData[i] & 0xFF)); |
| 157 | + sum += sample * sample; |
| 158 | + } |
| 159 | + double rms = Math.sqrt(sum / (audioData.length / 2)); |
| 160 | + |
| 161 | + System.out.println("📊 RMS Value: " + rms); // Debugging |
| 162 | + |
| 163 | + return rms < SILENCE_THRESHOLD; |
| 164 | + } |
| 165 | + |
| 166 | + // ✅ Save Audio to WAV File |
| 167 | + private void saveAudioToWAV(byte[] audioData, String filename) throws IOException { |
| 168 | + String filePath = "C:/Users/opc/Downloads/audio_logs/" + filename; |
| 169 | + Files.createDirectories(Paths.get("C:/Users/opc/Downloads/audio_logs/")); |
| 170 | + |
| 171 | + try (FileOutputStream fos = new FileOutputStream(filePath)) { |
| 172 | + fos.write(generateWAVHeader(audioData.length, 16000, 1)); // ✅ Proper WAV header |
| 173 | + fos.write(audioData); |
| 174 | + } |
| 175 | + |
| 176 | + System.out.println("💾 Saved WAV: " + filePath); |
| 177 | + } |
| 178 | + |
| 179 | + // ✅ Generate Correct WAV Header |
| 180 | + private byte[] generateWAVHeader(int dataSize, int sampleRate, int channels) { |
| 181 | + int totalDataLen = dataSize + 36; |
| 182 | + int byteRate = sampleRate * channels * 2; |
| 183 | + |
| 184 | + return new byte[]{ |
| 185 | + 'R', 'I', 'F', 'F', (byte) (totalDataLen & 0xff), (byte) ((totalDataLen >> 8) & 0xff), |
| 186 | + (byte) ((totalDataLen >> 16) & 0xff), (byte) ((totalDataLen >> 24) & 0xff), |
| 187 | + 'W', 'A', 'V', 'E', 'f', 'm', 't', ' ', |
| 188 | + 16, 0, 0, 0, 1, 0, (byte) channels, 0, |
| 189 | + (byte) (sampleRate & 0xff), (byte) ((sampleRate >> 8) & 0xff), |
| 190 | + (byte) ((sampleRate >> 16) & 0xff), (byte) ((sampleRate >> 24) & 0xff), |
| 191 | + (byte) (byteRate & 0xff), (byte) ((byteRate >> 8) & 0xff), |
| 192 | + (byte) ((byteRate >> 16) & 0xff), (byte) ((byteRate >> 24) & 0xff), |
| 193 | + (byte) (channels * 2), 0, 16, 0, |
| 194 | + 'd', 'a', 't', 'a', (byte) (dataSize & 0xff), (byte) ((dataSize >> 8) & 0xff), |
| 195 | + (byte) ((dataSize >> 16) & 0xff), (byte) ((dataSize >> 24) & 0xff) |
| 196 | + }; |
| 197 | + } |
| 198 | +} |
0 commit comments