I play a file through media player and I want to give options like speaker on/off, play though headset, bluetooth ,etc. I tried the below code which works well for android 2.2 but I want something that can also work for 2.2 and 4.0 both. Can you help me to programmatically turn the speaker on/off and playing via headphones?
AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); if(isOn){ audioManager.setMode(AudioManager.MODE_IN_CALL); audioManager.setMode(AudioManager.MODE_NORMAL); }else{ //Seems that this back and forth somehow resets the audio channel audioManager.setMode(AudioManager.MODE_NORMAL); audioManager.setMode(AudioManager.MODE_IN_CALL); } audioManager.setSpeakerphoneOn(isOn);
P.S: I have given this permission in manifest:
android.permission.MODIFY_AUDIO_SETTINGS
If you click on the Speaker button on the bottom right, and click on Mixer, it will show all programs that can use the speaker.
Something like this might work on some devices (I've only tested in on an XPeria P):
final static int FOR_MEDIA = 1; final static int FORCE_NONE = 0; final static int FORCE_SPEAKER = 1; Class audioSystemClass = Class.forName("android.media.AudioSystem"); Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class); setForceUse.invoke(null, FOR_MEDIA, FORCE_SPEAKER); // To get back to the default behaviour, use the combination FOR_MEDIA,FORCE_NONE.
The combination FOR_MEDIA, FORCE_SPEAKER
is typically only used internally to route the FM-radio audio to the loudspeaker (since the FM-radio requires you to have a wired headset / headphone plugged in to act as an antenna). Devices that don't have FM-radio functionality (or uses an alternative implementation) might ignore this combination of parameters, so this method would not work on such a device.
AudioManager mAudioMgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE); Button mVolumeButton = (Button)findViewById(R.id.btn_Volume); mVolumeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mAudioMgr.isWiredHeadsetOn()){ mAudioMgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE); mAudioMgr.setWiredHeadsetOn(false); mAudioMgr.setSpeakerphoneOn(true); mAudioMgr.setMode(AudioManager.MODE_IN_COMMUNICATION); Toast.makeText(getApplicationContext(), "SpeakerPhone On", Toast.LENGTH_LONG).show(); }else{ mAudioMgr.setMode(AudioManager.MODE_IN_COMMUNICATION); mAudioMgr.setSpeakerphoneOn(false); mAudioMgr.setWiredHeadsetOn(true); Toast.makeText(getApplicationContext(), "Wired Headset On", Toast.LENGTH_LONG).show(); } } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With