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();
}
}
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 ie 4th item
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.