Reputation: 628
In my application user selects the count like 1, 21, 51, 101, 108,like when he selected using buttons or radio button, the media player has to be repeated at number of time. If he selects 21, media player should repeat the playing of the music by 21 times. In my code, if I use while loop inside the for loop its blocking the UI, not allowing to stop or pause the play, if I did not use the while loop it plays only once. Please I need to solve it any one will be appreciated thanks in advance. Below I am posting my entire code
public class MainActivity extends Activity implements OnClickListener{
private MediaPlayer mp;
int count;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
findViewById(R.id.button_1).setOnClickListener(this);
findViewById(R.id.button_2).setOnClickListener(this);
findViewById(R.id.button_3).setOnClickListener(this);
findViewById(R.id.button_4).setOnClickListener(this);
findViewById(R.id.button_5).setOnClickListener(this);
findViewById(R.id.pause).setOnClickListener(this);
findViewById(R.id.stop).setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_1:
if (mp!=null) {
mp.release();
}
player(3);
break;
case R.id.button_2:
if (mp!=null) {
mp.release();
}
player(21);
break;
case R.id.button_3:
if (mp!=null) {
mp.release();
}
player(51);
break;
case R.id.button_4:
if (mp!=null) {
mp.release();
}
player(108);
break;
case R.id.button_5:
if (mp!=null) {
mp.release();
}
break;
case R.id.pause:
mp.pause();
break;
case R.id.stop:
mp.stop();
break;
}
}
private void player(int count) {
// TODO Auto-generated method stub
mp = MediaPlayer.create(this, R.raw.a);
for (int i=1; i<=count ; i++){
mp.start();
while(mp.isPlaying());
}
// mp.release();
}
@Override
protected void onDestroy() {
if(null!=mp){
mp.release();
}
super.onDestroy();
}
}
Upvotes: 1
Views: 4687
Reputation: 2828
you can achieve this by setting a yourCount integer that has the numbers you are going to repeat your sound and than simply do this
int count = 0;
mp.setOnCompletionListener(new OnCompletionListener()
@Override
public void onCompletion(MediaPlayer mp) {
if (count < yourCount) {
mp.start();
count++;
}
}
});
mp.start();
Upvotes: 5
Reputation: 1388
try this, Hope it helps
mp.setOnCompletionListener(new OnCompletionListener(){
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
// Count here and restart if required.
}});
Upvotes: 3