我在Playing multiple files in MediaPlayer one after other In android
找到了以下代码作为问题的答案当我运行它时,会播放3个声音,然后应用程序关闭并显示消息
遗憾的是,申请已停止。
onCompletion
方法中是否缺少某些内容?
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();
}
}
答案 0 :(得分:3)
改变这个:
public void onCompletion(MediaPlayer arg0) {
arg0.release();
if (currentTrack < tracks.length) {
currentTrack++;
arg0 = MediaPlayer.create(getApplicationContext(), tracks[currentTrack]);
arg0.setOnCompletionListener(this);
arg0.start();
}
}
到:
public void onCompletion(MediaPlayer arg0) {
arg0.release();
currentTrack++;
if (currentTrack < tracks.length) {
arg0 = MediaPlayer.create(getApplicationContext(), tracks[currentTrack]);
arg0.setOnCompletionListener(this);
arg0.start();
}
}
基本上你最后得到ArrayIndexOutofBoundException
becoz currentTrack是3而且索引3没有项目,即第4项