Java Sound refresh Lines list after attaching a microphone

前端 未结 2 1034
情书的邮戳
情书的邮戳 2021-01-12 18:58

I have a simple capture/playback Swing app that has to detect if there is no appropriate microphone attached to the computer and warn the user. After a lot of fiddling aroun

2条回答
  •  春和景丽
    2021-01-12 19:34

    Using the original post as inspiration, I came up with this as a means to detect when a mic is lost or gained. It detects (on my system) when a USB mic is plugged in or unplugged. I'm calling it from a background thread loop. The original method did not work for me as there is a built-in mic on the laptop, so I needed to detect the addition of second mic.

    ...
    //call this once somewhere to turn the caching period down for faster detection
        try
        {
            //try to set the caching period, defaults to something like 55 seconds
            com.sun.media.sound.JDK13Services.setCachingPeriod(5);
        }
        catch( Exception e)
        {
            System.err.println("exception attempting to call com.sun.media.sound.JDK13Services.setCachingPeriod->" + e);
        }
    ...
    
    private int lastNumMics = -1;
    private synchronized void micCheck()
    {
        Line.Info[] lineInfoArray = AudioSystem.getSourceLineInfo(Port.Info.MICROPHONE);
        int numMics = lineInfoArray == null ? 0 : lineInfoArray.length;
        if( lastNumMics > -1 )
        {
            if( numMics < lastNumMics )
            {
                //MICROPHONE_LOST
            }
            else if( numMics > lastNumMics )
            {
                //MICROPHONE_GAINED
            }
        }
        lastNumMics = numMics;
    }
    

提交回复
热议问题