我尝试播放两个声音,但这是第二个声音结束时的错误。我试图调试,但我没有发现任何事情告诉我我的问题。
这是我的代码:
public class MainActivity extends Activity {
private MediaPlayer mp;
private int[] sound = new int[2];
private int currentSound = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sound[0] = R.raw.sound_one;
sound[1] = R.raw.sound_two;
mp = MediaPlayer.create(this, sound[currentSound]);
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer arg0) {
if (currentSound < sound.length) {
currentSound++;
arg0 = MediaPlayer.create(getApplicationContext(),sound[currentSound]);
arg0.setOnCompletionListener(this);
arg0.start();
}
}
}
});
mp.start();
}
答案 0 :(得分:0)
当第一个声音完成时,currentSound < sound.length
同样意味着0 < 2
完成第二个声音后currentSound < sound.length
暗示1 < 2
并且进一步增加currentSound++
所以现在它值为2
。因此arg0 = MediaPlayer.create(getApplicationContext(),sound[currentSound]);
会抛出错误。 sound[currentSound]
是sound[2]
。
在currentSound++
if (currentSound < sound.length)
@Override
public void onCompletion(MediaPlayer arg0) {
currentSound++;
if (currentSound < sound.length) {
arg0 = MediaPlayer.create(getApplicationContext(),sound[currentSound]);
arg0.setOnCompletionListener(this);
arg0.start();
}
}