Java soundApi录制错误

时间:2016-02-28 03:49:39

标签: java audio audio-recording javasound

我正在尝试使用此代码录制16khz单声道.wav文件

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;

public class Main {

    public static void main(String[] args) {
        System.out.println("Say what you see..");

        try {
            AudioFormat format = new AudioFormat(
                    AudioFormat.Encoding.PCM_SIGNED, 16000, 8, 1, 4, 16000,
                    false);

            DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
            if (!AudioSystem.isLineSupported(info))
                System.out.println("Line not Supported");
            final TargetDataLine targetLine = (TargetDataLine) AudioSystem
                    .getLine(info);
            targetLine.open();

            System.out.println("Recording");
            targetLine.start();

            Thread thread = new Thread() {

                @Override
                public void run() {
                    AudioInputStream audioStream = new AudioInputStream(
                            targetLine);
                    File audioFile = new File("record.wav");
                    try {
                        AudioSystem.write(audioStream,
                                AudioFileFormat.Type.WAVE, audioFile);
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                    System.out.println("stopped recording");
                }

            };
            thread.start();
            Thread.sleep(5000);
            targetLine.stop();
            targetLine.close();
            System.out.println("Done");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

当我运行它时,我总是会收到此错误:

Line not Supported
java.lang.IllegalArgumentException: No line matching interface TargetDataLine supporting format PCM_SIGNED 16000.0 Hz, 8 bit, mono, 4 bytes/frame,  is supported.at javax.sound.sampled.AudioSystem.getLine(AudioSystem.java:476)at Main.main(Main.java:29)

ps:我用AudioFormat的不同参数测试了很多次它只在我尝试这些立体声和44.1khz

的参数时起作用
AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,44100,16,2,4,44100,false); 

1 个答案:

答案 0 :(得分:2)

您必须指定与AudioFormat支持的格式之一匹配的TargetDataLine

例如,我的Mac上的麦克风支持:

Supported Audio Formats

'未知采样率'意味着采样率并不重要。

我在这里看到的主要区别是你指定每帧4个字节,对于8位单声道,这应该是每帧1个字节。