Search code examples
androidaudiomedia-player

Play 2 audio files in same activity


MediaPlayer instrumental = new MediaPlayer();
MediaPlayer vocal = new MediaPlayer();

I need these 2 objects to work independently when I click the Play Button and should play separately.

The vocal should have its own progress bar which will indicate the volume of its audio without affecting the volume of the instrumental.

Think of this problem as running two audio with different controls for volume.


Solution

  • This can be done by setting seperate audio stream types on your MediaPlayer instances. I don't know if this will have any unintended consequences, I guess you are supposed to use STREAM_MUSIC for music... but it works.

    seek1 = (SeekBar) findViewById(R.id.seek1);
    seek2 = (SeekBar) findViewById(R.id.seek2);
    
    seek1.setOnSeekBarChangeListener(this);
    seek2.setOnSeekBarChangeListener(this);
    
    am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    
    seek1.setMax(am.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
    seek2.setProgress(am.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL));
    
    // Set up your MediaPlayers
    // Call the following lines before onPrepare()
    
    instrumental.setAudioStreamType(AudioManager.STREAM_MUSIC);
    vocal.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
    

    Then later in your onSeekBarChangeListener

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (seekBar.equals(seek1)) {
            am.setStreamVolume(AudioManager.STREAM_MUSIC, seekBar.getProgress(), 0);
        }
        else {
            am.setStreamVolume(AudioManager.STREAM_VOICE_CALL, seekBar.getProgress(), 0);
        }
    
    }