androidaudioheadphones

How to force sound file to play only with headphones in android


I am working on an app and I need to play a sound file only with headphones, no speakers, no earpiece weather headphone is plugged or not, on switch buttons' on or off state. I have written below code for that.

audioManager.setMode(AudioManager.STREAM_MUSIC);
                    if(mPrefs.getBoolean("flow_recording", false)){
                        audioManager.setWiredHeadsetOn(true);
                        audioManager.setSpeakerphoneOn(false);
                    }
                    else{
                        audioManager.setWiredHeadsetOn(false);
                        audioManager.setSpeakerphoneOn(true);
                    }
                    mPlayer.start();

but it still plays the audio with speakers when I unplug the headphone.

Please guide me to achieve this.


Solution

  • Ok I have resolved this issue with the help of this link

    Below is my working code:-

    audioManager.setMode(AudioManager.STREAM_MUSIC);
                if(mPrefs.getBoolean("flow_recording", false)){
                    /*audioManager.setWiredHeadsetOn(true);
                    audioManager.setSpeakerphoneOn(false);*/
                    if(audioManager.isWiredHeadsetOn() && mPlayer != null){
                        Log.e("HeadPhone", "Playing via headphone");
                        mPlayer.start();
                    }
                }
                else{
                    if(audioManager.isSpeakerphoneOn() && mPlayer != null){
                        Log.e("Speaker", "Playing via speaker");
                        mPlayer.start();
                    }
                    /*audioManager.setWiredHeadsetOn(false);
                    audioManager.setSpeakerphoneOn(true);*/
                }