Search code examples
javaandroidandroid-audiomanagerandroid-video-player

Disable internal and external speakers and allow only earphones to watch video or listen Audio


I have some videos of which audios sound should be available only through earphone, not from inbuilt speaker or external speakers. NOTE: It should not allow External Speakers with 3.5mm jack. What is the possibility to solve it? It will be great if anybody help me out with this.


Solution

  • Check if the headset is plugged in:

    private boolean isHeadphonesPlugged(){
            AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
            AudioDeviceInfo[] audioDevices = audioManager.getDevices(AudioManager.GET_DEVICES_ALL);
            for(AudioDeviceInfo deviceInfo : audioDevices){
                if(deviceInfo.getType()==AudioDeviceInfo.TYPE_WIRED_HEADPHONES
                        || deviceInfo.getType()==AudioDeviceInfo.TYPE_WIRED_HEADSET){
                    return true;
                }
            }
            return false;
        }
    

    In a separated thread checks if the headPhones are going to be plugged out using the method above(in that case you have to stop your mediaPlayer and apply your logic)!

    For reference