How to record audio with the specified audio device in Java?

时间:2015-08-07 02:19:48

标签: java audio javasound

I have two microphones attached to the computer (one internal and one USB based). I want to record corresponding audio with each of them.

The main record codes are something like:

class Record implements Runnable{
    byte bts[] = new byte[10000];
    public void run() { 
        baos = new ByteArrayOutputStream();     
        try {
            stopflag = false;
            while(stopflag != true)
            {                   
                int cnt = td.read(bts, 0, bts.length);
                if(cnt > 0)
                {
                    baos.write(bts, 0, cnt);
                }

                byte copyBts[] = bts;
                bais = new ByteArrayInputStream(copyBts);
                ais = new AudioInputStream(bais, af, copyBts.length/af.getFrameSize());
                try{
                    DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, af);
                    sd = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
                    sd.open(af);
                    sd.start();             

                    //read from audio stream
                    int Buffer_Size = 10000;
                    audioDataBuffer = new byte[Buffer_Size];                   
                    intBytes = ais.read(audioDataBuffer, 0,audioDataBuffer.length);                     
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if(baos != null){
                    baos.close();
                }   
            } catch (Exception e) {
                e.printStackTrace();
            }finally{                   
                td.close();                 
            }
        }
    }       
}

And I can list audio devices with this code. The result is like:

OS: Windows 8.1 6.3/x86
Java: 1.8.0_45 (Oracle Corporation)

Mixer: Direct Audio Device: DirectSound Playback [Primary Sound Driver]
Mixer: Direct Audio Device: DirectSound Playback [Speakers / HP (IDT High Definition Audio CODEC)]
Mixer: Direct Audio Device: DirectSound Capture [Primary Sound Capture Driver]
Mixer: Direct Audio Device: DirectSound Capture [Internal Microphone Array (IDT ]**//integrated device**
Mixer: Direct Audio Device: DirectSound Capture [Microphone (2- USB PnP Sound De]**//usb device**
...

Now how can I ask the program to just record audio from the usb device (or the integrated device) at a time?

1 个答案:

答案 0 :(得分:0)

找到您要使用的Mixer并替换

sd = (SourceDataLine) AudioSystem.getLine(dataLineInfo);

对齐
sd = (SourceDataLine) mixer.getLine(dataLineInfo);