Max D Max D - 3 months ago 8
Android Question

App Crashing when playing sounds in succession in MediaPlayer

I found the following code as an answer to a question here Playing multiple files in MediaPlayer one after other In android

When I run it, the 3 sounds are played but then the app closes with the message


unfortunately the application has stopped.


Is there something missing inside the
onCompletion
method?

public class MainActivity extends Activity implements MediaPlayer.OnCompletionListener {

int[] tracks = new int[3];
int currentTrack = 0;
private MediaPlayer mediaPlayer = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tracks[0] = R.raw.p46;
tracks[1] = R.raw.p52;
tracks[2] = R.raw.p55;
mediaPlayer = MediaPlayer.create(getApplicationContext(), tracks[currentTrack]);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
}

public void onCompletion(MediaPlayer arg0) {
arg0.release();
if (currentTrack < tracks.length) {
currentTrack++;
arg0 = MediaPlayer.create(getApplicationContext(), tracks[currentTrack]);
arg0.setOnCompletionListener(this);
arg0.start();
}
}

Answer

Change this:

public void onCompletion(MediaPlayer arg0) {
        arg0.release();
        if (currentTrack < tracks.length) {
            currentTrack++;
            arg0 = MediaPlayer.create(getApplicationContext(), tracks[currentTrack]);
            arg0.setOnCompletionListener(this);
            arg0.start();
        }
    }

to :

public void onCompletion(MediaPlayer arg0) {
        arg0.release();
        currentTrack++;
        if (currentTrack < tracks.length) {

            arg0 = MediaPlayer.create(getApplicationContext(), tracks[currentTrack]);
            arg0.setOnCompletionListener(this);
            arg0.start();
        }
    }

basically you are getting a ArrayIndexOutofBoundException becoz at last currentTrack is 3 and and there is no item at index 3 i.e 4th item