3 Replies Latest reply: Apr 11, 2011 8:54 AM by 853888 RSS

    Plug-in and Removal of sound devices

    853888
      Hi,

      We're having a problem with USB sound devices. When our application is running, we can't determine if the user has plugged in or removed a sound device. After the first call to AudioSystem.getMixerInfo(), it always returns the same list of devices.

      Is there any way to get the list of devices that are currently available?

      Here is some example code to illustrate the problem:
      import java.io.IOException;
      import java.util.List;
      import java.util.Vector;
      
      import javax.sound.sampled.AudioSystem;
      import javax.sound.sampled.Line;
      import javax.sound.sampled.Mixer;
      import javax.sound.sampled.SourceDataLine;
      import javax.sound.sampled.TargetDataLine;
      
      public class DeviceEnumerator {
          private static List<String> enumerateDevices(Class<?> lineClass) {
              List<String> ret = new Vector<String>();
      
              for (Mixer.Info mixerInfo : AudioSystem.getMixerInfo()) {
                  Mixer mixer = AudioSystem.getMixer(mixerInfo);
                  Line.Info lineInfo = new Line.Info(lineClass);
                  if (mixer.isLineSupported(lineInfo)) {
                      ret.add(mixer.getMixerInfo().getName());
                  }
              }
      
              return ret;
          }
      
          private static List<String> enumeratePlaybackDevices() {
              return enumerateDevices(SourceDataLine.class);
          }
      
          private static List<String> enumerateCaptureDevices() {
              return enumerateDevices(TargetDataLine.class);
          }
      
          private static void findAudioDevices() {
              List<String> playbackDevices = enumeratePlaybackDevices(), captureDevices = enumerateCaptureDevices();
      
              System.out.println("Found " + playbackDevices.size() + " playback devices:");
              for (String s : playbackDevices) {
                  System.out.println("  " + s);
              }
              System.out.println();
      
              System.out.println("Found " + captureDevices.size() + " capture devices:");
              for (String s : captureDevices) {
                  System.out.println("  " + s);
              }
              System.out.println();
          }
      
          public static void main(String[] args) {
              System.out.println("Press Enter to start ...");
              try {
                  System.in.read();
              } catch (IOException e) {
                  e.printStackTrace();
              }
      
              while (true) {
                  findAudioDevices();
                  try {
                      Thread.sleep(2000);
                  } catch (InterruptedException e) {
                      break;
                  }
              }
          }
      }