user3323951
user3323951

Reputation: 397

[Android]Only earphone sound when the earphone is plugged in

I want to sound only from the earphone when the earphone is plugged into android. (By alarm volume)

        AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
        audioManager.setStreamVolume(AudioManager.STREAM_ALARM,alarmVolume,0);

        mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        mediaPlayer.prepare();
        mediaPlayer.setLooping(false);

        mediaPlayer.start();

Upvotes: 0

Views: 223

Answers (1)

SpiritCrusher
SpiritCrusher

Reputation: 21053

For that you need to listen the wired headset state.

 private void registerWiredHeadsetIntentBroadcast() {
    IntentFilter filter = new IntentFilter("android.intent.action.HEADSET_PLUG");
    this.wiredHeadsetReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            int state = intent.getIntExtra("state", 0);
            int microphone = intent.getIntExtra("microphone", 0);
            boolean hasWiredHeadset = state == 1;
            isWiredHeadsetPlugged=hasWiredHeadset;
                switch (state) {
                    case 0:
                        //unplugged
                        audioManager.setWiredHeadsetOn(false);
                        audioManager.setSpeakerphoneOn(true);
                        break;
                    case 1:
                        //plugged
                        audioManager.setWiredHeadsetOn(true);
                        break;
                    default:
                }
        }
    };
    this.apprtcContext.registerReceiver(this.wiredHeadsetReceiver, filter);
}

Assign the AudioStreamType to audio manager and you are good to go.

Upvotes: 1

Related Questions