我尝试通过媒体播放两个声音时出错

时间:2014-05-30 17:51:47

标签: android android-mediaplayer

我尝试播放两个声音,但这是第二个声音结束时的错误。我试图调试,但我没有发现任何事情告诉我我的问题。

这是我的代码:

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

1 个答案:

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