首页 > 解决方案 > TargetDataline 返回 -1(Audiosystem.NOT_SPECIFIED)

问题描述

我正在尝试制作一个实时语音识别程序,但是当我尝试从 targetdataline 获取输入音量时,它返回 -1。这很奇怪,因为我确实指定了音频系统。

这甚至发生在我直接从文档中复制代码时。这是我的代码:

public void startRecognizer() throws LineUnavailableException {
    AudioFormat format = new AudioFormat(16000.0F, 16, 1, true, true);
    TargetDataLine line = null;
    DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); // format is an AudioFormat object
    if (!AudioSystem.isLineSupported(info)) {
        // Handle the error ...
        for (Line.Info i :AudioSystem.getTargetLineInfo(info)) {
            System.out.println(i.toString());
        }
        System.out.println("line not supported, exiting");
        System.exit(1);
    }

    try {
        line = (TargetDataLine) AudioSystem.getLine(info);
        line.open(format, 4096);
    } catch (LineUnavailableException ex) {
        System.out.println("line is unavailable, exiting...");
        //error code one for line not available.
        System.exit(1);
    }
    System.out.println(line.getLevel());


    ByteArrayOutputStream out  = new ByteArrayOutputStream();
    int numBytesRead= 0;
    byte[] data = new byte[line.getBufferSize() / 5];

    System.out.println("getting minimum soundlevel...");
    float minimumSound = Main.getApi().getConfigManager().getIO().getConfig().getFloat("minimumSound", 0.3F);
    while(true){
        line.start();
        System.out.println(line.getLevel() + ", " + minimumSound);
        if (line.getLevel() >= minimumSound){

            isWaiting = true;

            TargetDataLine finalLine = line;
            Thread t = new Thread(() -> {
                try {
                    Thread.sleep(2000);
                    if (finalLine.getLevel() <= minimumSound) isWaiting = false;
                    System.out.println("stopped talking..");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            t.start();
            while(isWaiting){
                numBytesRead = line.read(data, 0, data.length);
                out.write(data, 0, numBytesRead);
            }
            t.stop();
            line.stop();

            System.out.println(data + ", " + numBytesRead);
        }
    }
}

并且根本没有错误。

标签: java

解决方案


推荐阅读