Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Plug-in and Removal of sound devices

853888Apr 8 2011 — edited Apr 11 2011
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;
            }
        }
    }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 9 2011
Added on Apr 8 2011
3 comments
1,907 views