如何在Java中捕获声音?

时间:2018-12-02 18:15:36

标签: java audio

我正在尝试捕获PC的声音。我已经成功地捕获了通过TargetDataLine进入麦克风的声音,但是我找不到捕获来自扬声器的声音的方法。

我一直在观看mixer,但没有设法捕捉声音。我想知道是否有人这样做,以及您能否给我一些从哪里开始的线索。

1 个答案:

答案 0 :(得分:0)

尽管,您的问题并不是真正按照“规则”进行的,但这是一个代码片段:

private byte[] record() throws LineUnavailableException {
    AudioFormat format = AudioUtil.getAudioFormat(audioConf);
    DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

    // Checks if system supports the data line
    if (!AudioSystem.isLineSupported(info)) {
        LOGGER.error("Line not supported");
        System.exit(0);
    }

    microphone = (TargetDataLine) AudioSystem.getLine(info);
    microphone.open(format);
    microphone.start();

    LOGGER.info("Listening, tap enter to stop ...");

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int numBytesRead;
    byte[] data = new byte[microphone.getBufferSize() / 5];

    // Begin audio capture.
    microphone.start();

    // Here, stopped is a global boolean set by another thread.
    while (!stopped) {
        // Read the next chunk of data from the TargetDataLine.
        numBytesRead = microphone.read(data, 0, data.length);
        // Save this chunk of data.
        byteArrayOutputStream.write(data, 0, numBytesRead);
    }

    return byteArrayOutputStream.toByteArray();
}

从此处获取更多信息: https://www.programcreek.com/java-api-examples/?class=javax.sound.sampled.TargetDataLine&method=read