Play 2 different audio streams on left and right speaker

Either approaches 1) 2) should work as you said.

Regarding approach 1), if you want to play different stream simultaneously you could write both channels with different data in the same loop, without using two loops. In order to set the volume per channel, you can use the AudioTrack's method setStereoVolume(float leftGain, float rightGain).

Since MediaPlayer is an high-level API it doesn't offer this level of specificity; a workaround could be to save the audio data to a file (muting the left/right channel) and play it as a regular media element using MediaPlayer.


UPDATE:

save the audio data to a file (muting the left/right channel)

To do this, assuming that you have your audio data in the AudioTrack-compatible format (PCM), you just need to process the data as you said (muting one channel by resetting part of the array) and then save the array/buffer to a file as WAV/PCM. Take a look here for more detail and code about how to save WAV files.


I used 2 instances of mediaplayer and tried to play two seperate music tracks on earphones and it worked like a charm. it played one track on the left and an another on the right.

MediaPlayer mediaPlayer1 = MediaPlayer.create(this, R.raw.lenka);
MediaPlayer mediaPlayer2 = MediaPlayer.create(this, R.raw.faded);
final int sessionIdA = mediaPlayer1.getAudioSessionId();
final int sessionIdB = mediaPlayer2.getAudioSessionId();
mediaPlayer1.setLooping(true);
mediaPlayer2.setLooping(true);
mediaPlayer1.setVolume(0, 1);
mediaPlayer2.setVolume(1, 0);
mediaPlayer1.start();
mediaPlayer2.start(); 

Tags:

Audio

Android