Skip to content

Instantly share code, notes, and snippets.

@alanwhite
Created September 26, 2023 07:45
Show Gist options
  • Save alanwhite/8ec31d2aced6a741d92602771b37dba6 to your computer and use it in GitHub Desktop.
Save alanwhite/8ec31d2aced6a741d92602771b37dba6 to your computer and use it in GitHub Desktop.
List microphones in java
package xyz.arwhite;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.Line.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
public class miclist {
public record Microphone(Mixer mixer, DataLine target) {}
Map<String, List<Microphone>> mics = new HashMap<>();
private void buildMicList() {
Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
for (Mixer.Info mixerInfo1 : mixerInfo) {
Mixer mixer = AudioSystem.getMixer(mixerInfo1);
Line.Info[] targetLines = mixer.getTargetLineInfo();
for ( Info line : targetLines ) {
try {
var targetLine = AudioSystem.getLine(line);
if ( targetLine instanceof DataLine ) {
DataLine dataLine = (DataLine) targetLine;
var micList = mics.get(mixer.getMixerInfo().getName());
if ( micList == null )
micList = new ArrayList<Microphone>();
micList.add(new Microphone(mixer, dataLine));
mics.put(mixer.getMixerInfo().getName(), micList);
}
} catch(LineUnavailableException e) {
System.err.println(e.getMessage());
}
}
}
}
private void printMics() {
mics.forEach((name, lineList) -> {
System.out.println(name);
lineList.forEach(mic -> {
AudioFormat audioFormat = mic.target.getFormat();
System.out.println("\t\t\tChannels = " + audioFormat.getChannels());
System.out.println("\t\t\tEncoding = " + audioFormat.getEncoding());
System.out.println("\t\t\tFrame Rate = " + audioFormat.getFrameRate());
System.out.println("\t\t\tSample Rate = " + audioFormat.getSampleRate());
System.out.println("\t\t\tSample Size (bits) = " + audioFormat.getSampleSizeInBits());
System.out.println("\t\t\tBig Endian = " + audioFormat.isBigEndian());
System.out.println("\t\t\tLevel = " + mic.target.getLevel());
});
});
}
public static void main(String[] args) {
var mics = new miclist();
mics.buildMicList();
mics.printMics();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment