Search code examples
androidaudiosoundpoolandroid-audiomanagerheadphones

Audio through built-in speakers when earphones are plugged in headphone jack in Android


In my application, there is one Card Reader which uses Audio Jack of devices.Now, my problem is I want to produce sound from built-in speakers when Card Reader is intact in HeadPhone Jack of the device.

Here are the codes I have tried:

1) Using Reflection Methods

Class audioSystemClass;
                try {
                     audioSystemClass = Class
                            .forName("android.media.AudioSystem");

                    Method setForceUse = audioSystemClass.getMethod(
                            "setForceUse", int.class, int.class);
                    // First 1 == FOR_MEDIA, second 1 == FORCE_SPEAKER. To go
                    // back to the default
                    // behavior, use FORCE_NONE (0).
                    setForceUse.invoke(null, 1, 1);
                    final float maxVolume = mAudioManager
                            .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                    soundPool.play(soundID, maxVolume, maxVolume, 1, 0, 1f);


                } catch (ClassNotFoundException e) {
                    Log.e("Test", e.toString());
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    Log.e("Test", e.toString());
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    Log.e("Test", e.toString());
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    Log.e("Test", e.toString());
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    Log.e("Test", e.toString());
                    e.printStackTrace();
                }

2) Using setMode method

mAudioManager.setMode(AudioManager.MODE_IN_CALL);
                mAudioManager.setSpeakerphoneOn(true);
                float maxVolume = mAudioManager
                        .getStreamMaxVolume(AudioManager.STREAM_RING);
                soundPool.play(soundID, maxVolume, maxVolume, 1, 0, 1f);

But these both codes are running in only those devices which have default FM application. But I want to have this functionality in all devices.

Please share your experience !!


Solution

  • Alternatively, if you initialize your SoundPool to STREAM_VOICE_CALL, as:

    SoundPool spool = new SoundPool(1,AudioManager.STREAM_VOICE_CALL, 0)

    then also your audio should be routed to loudspeaker with any of the way you have mentioned above. I tried and its working on phones even without default FM.