3

I'm currently developing application and i want to control playing sound file on different headphones sides ex the first time on the left side and second time on the right side is there any way to achieve this ?

user101530
  • 87
  • 12

1 Answers1

5

Yes there is a way. MediaPlayer.setVolume(float leftVolume,float rightVolume).

In the following snippet we're playing an .mp3 file contained in assets folder(note if you have multiple files in the folder you should check this answer). By pressing one of the Button objects the song is played only out of the left or the right headphone :

MediaPlayer AudioObj = new MediaPlayer();
    AudioObj.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(final MediaPlayer mediaPlayer) {
            findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);
            Button btnl = (Button) findViewById(R.id.btnPlayleft);
            Button btnr = (Button) findViewById(R.id.btnPlayright);
            btnl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mediaPlayer.setVolume(1, 0);
                    mediaPlayer.start();
                }
            });
            btnr.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mediaPlayer.setVolume(0, 1);
                    mediaPlayer.start();
                }
            });
        }
    });
    AudioObj.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        AssetFileDescriptor afd = getAssets().openFd("audio.mp3");
        AudioObj.setDataSource(afd.getFileDescriptor());
    }catch (IOException e){}
    AudioObj.prepareAsync(); 

P.S.

The audio file must be stereo.

Whether you want to check if the headset are plugged or not before playing the audio in order to prompt a message or do something else :

AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
if(!audioManager.isSpeakerphoneOn()){
//prompt a message or do something else
} 
Community
  • 1
  • 1
n1nsa1d00
  • 856
  • 9
  • 23
  • +1 Works fine with 2 devices. Vivo and Oppo. But on Redmi Note 5 Pro, it is not working. It's playing sound on both(Left and Right) equally. That means code isn't taking effect. 1 difference between the Redmi note 5 pro and other 2 is Android version. Redmi has Android 9 and other 2 has Android 8 and 5. So maybe it is Android 9 issue? Please update answer if you have solution. Thanks :) – Jaydip Kalkani Dec 23 '19 at 08:05