Reputation: 35
i want to play MediaPlayer for 1 second. How to set Duration in this code..
player = MediaPlayer.create(getApplicationContext(), R.raw.beepsound);
player.start();
CountDownTimer Timer = new CountDownTimer(1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
player.start();
}
@Override
public void onFinish() {
// TODO Auto-generated method stub
player.stop();
}
};
Timer.start();
Upvotes: 2
Views: 7532
Reputation: 1441
You could use TimerTask to schedule a MediaPlayer.stop() to run after 1 secs.
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
MediaPlayer.stop()
}
};
timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 20000 ms
}
can u try this one
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
}
}, timeout);
Upvotes: 3
Reputation: 1409
You don't need to do anything on the onTick
method.
Try this code:
player = MediaPlayer.create(getApplicationContext(), R.raw.beepsound);
player.start();
CountDownTimer timer = new CountDownTimer(1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
// Nothing to do
}
@Override
public void onFinish() {
if (player.isPlaying()) {
player.stop();
player.release();
}
}
};
timer.start();
If you look at the constructor:
public CountDownTimer (long millisInFuture, long countDownInterval)
millisInFuture
- The number of millis in the future from the call to start() until the countdown is done and onFinish() is called.
So onFinish()
will be called after 1 second (1000 millisecond = 1second).
Ref: http://developer.android.com/reference/android/os/CountDownTimer.html#CountDownTimer(long, long)
Upvotes: 2