Skip to content

Instantly share code, notes, and snippets.

@HyCraftHD
Last active December 23, 2019 11:36
Show Gist options
  • Save HyCraftHD/fc8c8aaf9894b573bcb1c0a41b696140 to your computer and use it in GitHub Desktop.
Save HyCraftHD/fc8c8aaf9894b573bcb1c0a41b696140 to your computer and use it in GitHub Desktop.
Simultaneously recorde from two mics and play it back to one speaker in java
import javax.sound.sampled.*;
public class Test {
private static final AudioFormat FORMAT = new AudioFormat(48000, 16, 2, true, false);
private static final DataLine.Info MIC_INFO = new DataLine.Info(TargetDataLine.class, FORMAT);
private static final DataLine.Info SPEAKER_INFO = new DataLine.Info(SourceDataLine.class, FORMAT);
public static void main(String[] args) throws LineUnavailableException {
final TargetDataLine micro1 = findMicrophoneOrUseDefault("name");
openTargetLine(micro1);
final TargetDataLine micro2 = findMicrophoneOrUseDefault("name");
openTargetLine(micro2);
final Mixer speakerMixer = findMixer("", SPEAKER_INFO);
final SourceDataLine speaker1 = (SourceDataLine) speakerMixer.getLine(SPEAKER_INFO);
openSourceLine(speaker1);
final SourceDataLine speaker2 = (SourceDataLine) speakerMixer.getLine(SPEAKER_INFO);
openSourceLine(speaker2);
final byte[] buffer1 = new byte[960 * 2 * 2];
final byte[] buffer2 = new byte[960 * 2 * 2];
while (true) {
micro1.read(buffer1, 0, buffer1.length);
micro2.read(buffer2, 0, buffer2.length);
speaker1.write(buffer1, 0, buffer1.length);
speaker2.write(buffer2, 0, buffer2.length);
}
}
private static void openTargetLine(TargetDataLine line) {
try {
line.open(FORMAT, 960 * 2 * 2 * 4);
line.start();
} catch (LineUnavailableException ex) {
}
}
private static void openSourceLine(SourceDataLine line) {
try {
line.open(FORMAT, 960 * 2 * 2 * 4);
line.start();
} catch (LineUnavailableException ex) {
}
}
public static Mixer findMixer(String name, Line.Info lineInfo) {
Mixer defaultMixer = null;
for (Mixer.Info mixerInfo : AudioSystem.getMixerInfo()) {
final Mixer mixer = AudioSystem.getMixer(mixerInfo);
if (mixer.isLineSupported(lineInfo)) {
if (mixerInfo.getName().equals(name)) {
return mixer;
}
if (defaultMixer == null) {
defaultMixer = mixer;
}
}
}
return defaultMixer;
}
private static TargetDataLine findMicrophoneOrUseDefault(String name) {
try {
for (Mixer.Info info : AudioSystem.getMixerInfo()) {
final Mixer mixer = AudioSystem.getMixer(info);
if (mixer.isLineSupported(MIC_INFO) && info.getName().equals(name)) {
return (TargetDataLine) mixer.getLine(MIC_INFO);
}
}
return (TargetDataLine) AudioSystem.getLine(MIC_INFO);
} catch (LineUnavailableException ex) {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment