0

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

2 回答 2

2

您无需对该onTick方法执行任何操作。

试试这个代码:

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

如果您查看构造函数:

public CountDownTimer (long millisInFuture, long countDownInterval)

millisInFuture- 从调用 start() 到倒计时完成并调用 onFinish() 的未来毫秒数。所以onFinish()将在 1 秒后调用(1000 毫秒 = 1 秒)。

参考: http: //developer.android.com/reference/android/os/CountDownTimer.html#CountDownTimer (long , long)

于 2013-04-17T12:08:43.257 回答
2

您可以使用 TimerTask 安排 MediaPlayer.stop() 在 1 秒后运行。

TimerTask doAsynchronousTask = new TimerTask() {       
        @Override
        public void run() {
            MediaPlayer.stop()
        }
    };
    timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 20000 ms
     }

你能试试这个吗

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        if (mediaPlayer.isPlaying())
            mediaPlayer.stop();
    }
}, timeout);
于 2013-04-17T12:13:49.907 回答