3
3
import java .nio .file .*;
4
4
import java .util .concurrent .*;
5
5
import java .util .ArrayList ;
6
+ import javax .sound .sampled .AudioFormat ;
7
+ import javax .sound .sampled .AudioInputStream ;
8
+ import javax .sound .sampled .AudioSystem ;
6
9
7
10
public class VoskClient {
8
11
@@ -21,23 +24,47 @@ public void onTextMessage(WebSocket websocket, String message) {
21
24
});
22
25
ws .connect ();
23
26
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 ();
38
59
60
+ } catch (Exception ex ) {
61
+ ex .printStackTrace ();
62
+ }
63
+ } catch (Exception e ) {
64
+ e .printStackTrace ();
65
+ }
39
66
return results ;
40
- }
67
+ }
41
68
42
69
public static void main (String [] args ) throws Exception {
43
70
VoskClient client = new VoskClient ();
0 commit comments