我下面的程序通过从麦克风录制5秒钟来工作,然后它将自动重播它。但是我从将TargetDataLine转换为Audio.getLine()时遇到错误。任何帮助都非常有用!

public class Audio3 {

public static void main(String[] args) throws LineUnavailableException, InterruptedException {

    AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100, 16, 2, 4, 44100, false);

    DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
    final SourceDataLine sourceLine = (SourceDataLine)AudioSystem.getLine(info);
    sourceLine.open();

    info = new DataLine.Info(SourceDataLine.class, format);
    final TargetDataLine targetLine = (TargetDataLine) AudioSystem.getLine(info);
    targetLine.open();

    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    Thread sourceThread = new Thread() {

        @Override
        public void run() {
            sourceLine.start();

            while(true) {
                //out.size() also works fine
                sourceLine.write(out.toByteArray(), 0, out.toByteArray().length);
            }
        }
    };


    Thread targetThread = new Thread() {

        @Override
        public void run() {
            targetLine.start();
            byte[] data = new byte[targetLine.getBufferSize() / 5];
            int readBytes;

            while(true) {
                readBytes = targetLine.read(data, 0, data.length);
                out.write(data, 0, readBytes);
            }
        }
    };

}
}

最佳答案

SourceDataLine.class更改为TargetDataLine.class:

    info = new DataLine.Info(TargetDataLine.class, format); // changed
    final TargetDataLine targetLine = (TargetDataLine) AudioSystem.getLine(info);
    targetLine.open();

10-08 00:01