Search code examples
javawindowsmicrophone

How to detect if a microphone is used by any application


I wrote a program that changes my light depending on whether I'm in a meeting or not. The easiest way to detect this is to check if the microphone is on. Currently, I check if a microphone icon appears on the screen (OpenCv): enter image description here

I'm sure it's not the most optimal solution. Is there any way in Java to detect the fact that a microphone is being used?


Solution

  • Thanks to Eskandar Abedini I was able to do it! Below is the entire code:

    public enum RegistryType {
    
        MICROPHONE("microphone"),
        WEBCAM("webcam");
    
        private final String pathValue;
    
        RegistryType(String pathValue) {
            this.pathValue = pathValue;
        }
    
        public String getNonPackagePath() {
            return "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\CapabilityAccessManager\\ConsentStore\\" + pathValue + "\\NonPackaged";
        }
    
    }
    
    public class RegistryManager {
    
        private static final String LAST_USED_TIME_STOP = "LastUsedTimeStop";
        private static final Long LAST_USED_TIME_STOP_VALUE = 0L;
    
        private RegistryManager() {
        }
    
        public static boolean isMicrophoneWorking() {
            return isDeviceWorking(MICROPHONE);
        }
    
        public static boolean isWebcamWorking() {
            return isDeviceWorking(WEBCAM);
        }
        private static boolean isDeviceWorking(final RegistryType registryType) {
            final String[] folders = Advapi32Util.registryGetKeys(WinReg.HKEY_CURRENT_USER, registryType.getNonPackagePath());
            return Arrays.stream(folders)
                    .map(folder -> registryType.getNonPackagePath() + "\\" + folder)
                    .map(register -> Advapi32Util.registryGetLongValue(WinReg.HKEY_CURRENT_USER, register, LAST_USED_TIME_STOP))
                    .anyMatch(lastUsedTimeStop -> LAST_USED_TIME_STOP_VALUE.compareTo(lastUsedTimeStop) >= 0);
        }
    
    }
    

    And I also had to use: https://github.com/java-native-access/jna