package org.example;

import org.vosk.LibVosk;
import org.vosk.LogLevel;
import org.vosk.Model;
import org.vosk.Recognizer;
import javax.sound.sampled.*;
import java.io.IOException;

// 持续监听
public class demo1 {

    public static void main(String[] args) throws IOException {
        LibVosk.setLogLevel(LogLevel.DEBUG);

        // 设置音频格式
        AudioFormat format = new AudioFormat(16000, 16, 1, true, false);
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

        // 检查是否支持该音频格式
        if (!AudioSystem.isLineSupported(info)) {
            System.out.println("不支持的音频格式");
            System.exit(0);
        }

        // 获取并打开音频输入线
        TargetDataLine microphone;
        try {
            microphone = (TargetDataLine) AudioSystem.getLine(info);
            microphone.open(format);
        } catch (LineUnavailableException e) {
            e.printStackTrace();
            return;
        }

        // 创建Vosk识别器
        try (Model model = new Model("src\\main\\resources\\model\\vosk-model-cn-0.22");
             Recognizer recognizer = new Recognizer(model, 16000)) {

            // 开始录音
            microphone.start();
            System.out.println("语言识别模型载入完成...");
            System.out.println("开始录音...");

            byte[] buffer = new byte[4096];
            int bytesRead;

            while (true) { // 持续读取麦克风输入
                bytesRead = microphone.read(buffer, 0, buffer.length);
                if (bytesRead > 0) {
                    recognizer.acceptWaveForm(buffer, bytesRead);
                    String result = recognizer.getPartialResult(); // 获取部分识别结果
                    System.out.println(result);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭麦克风
            if (microphone != null && microphone.isOpen()) {
                microphone.stop();
                microphone.close();
            }
        }
    }

}
