Skip to content

Commit 5db5b0e

Browse files
authored
Changed example reading file to actually connect to Vosk server (#250)
* Changed example to actually connect to Vosk server * Reverted hostname
1 parent 5d155de commit 5db5b0e

File tree

1 file changed

+42
-15
lines changed

1 file changed

+42
-15
lines changed

client-samples/java/src/main/java/VoskClient.java

Lines changed: 42 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
import java.nio.file.*;
44
import java.util.concurrent.*;
55
import java.util.ArrayList;
6+
import javax.sound.sampled.AudioFormat;
7+
import javax.sound.sampled.AudioInputStream;
8+
import javax.sound.sampled.AudioSystem;
69

710
public class VoskClient {
811

@@ -21,23 +24,47 @@ public void onTextMessage(WebSocket websocket, String message) {
2124
});
2225
ws.connect();
2326

24-
FileInputStream fis = new FileInputStream(new File(path));
25-
DataInputStream dis = new DataInputStream(fis);
26-
byte[] buf = new byte[8000];
27-
while (true) {
28-
int nbytes = dis.read(buf);
29-
if (nbytes < 0) break;
30-
recieveLatch = new CountDownLatch(1);
31-
ws.sendBinary(buf);
32-
recieveLatch.await();
33-
}
34-
recieveLatch = new CountDownLatch(1);
35-
ws.sendText("{\"eof\" : 1}");
36-
recieveLatch.await();
37-
ws.disconnect();
27+
int totalFramesRead = 0;
28+
File fileIn = new File(path);
29+
try {
30+
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(fileIn);
31+
AudioFormat format = audioInputStream.getFormat();
32+
int bytesPerFrame = format.getFrameSize();
33+
if (bytesPerFrame == AudioSystem.NOT_SPECIFIED) {
34+
bytesPerFrame = 1;
35+
}
36+
37+
// Let Vosk server now the sample rate of sound file
38+
ws.sendText("{ \"config\" : { \"sample_rate\" : " + (int)format.getSampleRate() + " } }");
39+
40+
// Set an arbitrary buffer size of 1024 frames.
41+
int numBytes = 1024 * bytesPerFrame;
42+
byte[] audioBytes = new byte[numBytes];
43+
try {
44+
int numBytesRead = 0;
45+
int numFramesRead = 0;
46+
// Try to read numBytes bytes from the file.
47+
while ((numBytesRead = audioInputStream.read(audioBytes)) != -1) {
48+
// Calculate the number of frames actually read.
49+
numFramesRead = numBytesRead / bytesPerFrame;
50+
totalFramesRead += numFramesRead;
51+
recieveLatch = new CountDownLatch(1);
52+
ws.sendBinary(audioBytes);
53+
recieveLatch.await();
54+
}
55+
recieveLatch = new CountDownLatch(1);
56+
ws.sendText("{\"eof\" : 1}");
57+
recieveLatch.await();
58+
ws.disconnect();
3859

60+
} catch (Exception ex) {
61+
ex.printStackTrace();
62+
}
63+
} catch (Exception e) {
64+
e.printStackTrace();
65+
}
3966
return results;
40-
}
67+
}
4168

4269
public static void main(String[] args) throws Exception {
4370
VoskClient client = new VoskClient();

0 commit comments

Comments
 (0)