Search code examples
androidandroid-audiomanager

how to play sound file in single headphone side


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 ?


Solution

  • 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
    }