Reputation: 125
I made a sound in the list on the button.
int i = 0;
...
void nextTrack(int i)
{
mSound = new int [] {
R.raw.error_one,
R.raw.error_two,
R.raw.error_three
};
mp = MediaPlayer.create(getActivity(), mSound[i]);
mp.start();
}
...
@Override
public void onClick(View v) {
nextTrack(i);
i++;
}
But after the sound R.raw.error_three, the application crashes.
UPD.: I need to after the third sound again sounded the first
Logs.:
Upvotes: 0
Views: 60
Reputation: 3503
Im guessing you want to play Sound 1 after Sound three again. Then just add something like this :
@Override
public void onClick(View v) {
nextTrack(i);
i++;
if(i > mSound.length)
i = 0;
}
}
Upvotes: 0
Reputation: 4124
Out of bounds exception, because there is no mSound[3]
, only 0-2, total 3 elements.
void nextTrack(int i) {
mSound = new int [] {
R.raw.error_one,
R.raw.error_two,
R.raw.error_three
};
mp = MediaPlayer.create(getActivity(), mSound[i % 3]);
mp.start();
}
You can use i % 3
to replace i
in nextTrack
method, so the sound play by loop( sound[0], sound[1], sound[2], sound[0].... )
Use i % 3
, so the value will always be 0
, 1
or 2
.
See official doc of the %
operator.
Upvotes: 2
Reputation: 12378
Your need put condition in your onClick()
, here you need to make sure array index should always be less than the length of the array
@Override
public void onClick(View v) {
if(i < mSound.length){
nextTrack(i);
i++;
}
}
Upvotes: 0