1

我正在尝试从给定的混音器中读取音频字节,在这种情况下,是来自 Windows 系统的立体声混音。该项目由2部分组成。一个通过套接字(引发异常的那个)将 AudioFormat 和混音器 ID 发送到第二个,该套接字从混音器打开给定的行,以便它可以读取音频字节并将它们发送到第三方软件。

执行此任务的代码如下...

        try {
        line = (TargetDataLine) mixer.getLine(info);
        line.open(format);

        int bytesRead, CHUNK_SIZE = 4096;
        byte[] data = new byte[line.getBufferSize() / 5];

        line.start();

        while (true) {
            bytesRead = line.read(data, 0, CHUNK_SIZE); // Exception thrown in here.
            stdout.write(data, 0, bytesRead);
            stdout.flush();
        }

    } catch (LineUnavailableException ex) {
        System.out.println("Line is unavailable.");
        ex.printStackTrace();
    }

具体的错误信息如下...

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 800
      at com.sun.media.sound.DirectAudioDevice$DirectTDL.read(Unknown Source)
      at org.Main.main(Main.java:69)

这个错误让我感到惊讶,因为几个月前测试了完全相同的代码,并且可以通过标准输出完美地发送字节。

更新:索引800范围是 8 位音频格式,如果我选择 16 位,超出范围异常会说1600

4

1 回答 1

0

Your problem is the infinite loop due to the while(true) section. You read infinitely the line object which is an array, which means that has a specific length. So after 800 loops you reach the bounds of the array and there is no other object to read. This is why you get that type of Exception.

The solution to this problem is to check for the array length inside your while loop condition.

Of course you can perform this job with Stream feature of Java 8.

Forgive me for the lack of code samples. I am writing this answer through my phone.

于 2017-12-03T19:04:23.767 回答