import javax.sound.sampled.*;
public static class AudioCapture {
private AudioFormat format;
private float sampleRate;
private int sampleSizeInBits;
private int channels;
private org.vosk.Recognizer recognizer;
import java.nio.charset.Charset;
private final Charset UTF8_CHARSET = Charset.forName("UTF-8");
private final Charset PREVIOUSCHARSET = Charset.forName("CP1253");
public AudioCapture(float sampleRate, int sampleSizeInBits, int channels, org.vosk.Recognizer recognizer) {
this.sampleRate = sampleRate;
this.sampleSizeInBits = sampleSizeInBits;
this.channels = channels;
this.recognizer = recognizer;
this.format = new AudioFormat(sampleRate, sampleSizeInBits, channels, true, false);
subQvEvent("logs", "AudioCapture initialized with sampleRate: " + sampleRate + ", sampleSizeInBits: " + sampleSizeInBits + ", channels: " + channels);
}
private TargetDataLine line;
private boolean running = false;
public void startRecording() {
subQvEvent("logs", "Start recording...");
try {
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
if (!AudioSystem.isLineSupported(info)) {
subQvEvent("logs", "Line not supported");
return;
} else {
subQvEvent("logs", "Line supported");
}
line = (TargetDataLine) AudioSystem.getLine(info);
line.open(format);
line.start();
running = true;
new Thread(() -> {
byte[] buffer = new byte[1024];
while (running) {
int numRead = line.read(buffer, 0, buffer.length);
if (numRead > 0) {
boolean result = recognizer.acceptWaveForm(buffer, numRead);
String resultText;
if (result) {
resultText = recognizer.getResult();
} else {
resultText = recognizer.getPartialResult();
}
byte ptext[] = resultText.getBytes(PREVIOUSCHARSET);
String ppv = new String(ptext, UTF8_CHARSET);
subQvEvent("recognition_result", ppv);
}
}
line.drain();
line.close();
subQvEvent("logs", "Recording stopped.");
}).start();
} catch (LineUnavailableException e) {
subQvEvent("logs", "Line unavailable: " + e.getMessage());
}
}
public void stopRecording() {
subQvEvent("logs", "Stopping recording...");
running = false;
if (line != null) {
line.stop();
line.close();
line = null;
}
}
private void subQvEvent(String eventName, Object data) {
ba.raiseEventFromUI(null, eventName.toLowerCase() + "_qv", new Object[]{data});
}
}