gpt4 book ai didi

java - 在 MediaPlayer 中连续播放声音时应用程序崩溃

转载 作者:搜寻专家 更新时间:2023-11-01 08:33:12 25 4
gpt4 key购买 nike

我找到了以下代码作为此处问题的答案 Playing multiple files in MediaPlayer one after other In android

当我运行它时,会播放 3 种声音,但随后应用会关闭并显示消息

unfortunately the application has stopped.

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();
}
}

最佳答案

改变这个:

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 因为最后 currentTrack 是 3 并且在索引 3 处没有项目,即第 4 项

关于java - 在 MediaPlayer 中连续播放声音时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39025197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com