如何在android中设置媒体播放器持续时间

时间:2013-04-17 11:44:16

标签: android

我想玩MediaPlayer 1秒钟。如何在此代码中设置持续时间..

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

2 个答案:

答案 0 :(得分:1)

您无需对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()的未来毫秒数。 因此{1}将在1秒后被调用(1000毫秒= 1秒)。

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

答案 1 :(得分:1)

您可以使用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);