[英]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 我在这里找到以下代码作为问题的答案: 在MediaPlayer中一个接一个地播放多个文件
When I run it, the 3 sounds are played but then the app closes with the message 当我运行它时,会播放3种声音,但应用程序会关闭并显示消息
unfortunately the application has stopped.
不幸的是,该应用程序已停止。
Is there something missing inside the onCompletion
method? 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();
}
}
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 基本上你在最后一个currentTrack上得到一个
ArrayIndexOutofBoundException
becoz是3,并且索引3上没有项目,即第4个项目
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.