如何以编程方式在给定时间暂停/停止MediaPlayer Android?

时间:2017-03-09 16:25:05

标签: android android-mediaplayer

我有用于在Android中播放声音的mediaPlayer,我们希望根据开始时间和结束时间播放文件 例如:

start 10370 ,end: 14759 [OR] start 4754 ,end: 7836

我使用此代码解决了我的问题,但它并不完美 Pause/Stop MediaPlayer Android at given time programmatically

我的代码:

mediaPlayer.setDataSource(fd);
mediaPlayer.prepare();
mediaPlayer.seekTo(words.getW_start());
mediaPlayer.start();
handler.postDelayed(stopPlayerTask, words.getW_end());

你知道为什么这些时间的代码不起作用吗?

1 个答案:

答案 0 :(得分:0)

我可以解决问题。完整代码:

mediaPlayer.setDataSource(fd);
mediaPlayer.prepare();
mediaPlayer.seekTo(words.getW_start());
mediaPlayer.start();
new CountDownTimer(endTime, 10) {
 public void onTick(long millisUntilFinished) {

 if(MediaPlayerUtility.getTime(mediaPlayer)>=endTime){
      mediaPlayer.stop();
    }

         }

    public void onFinish() {


                            }
     }.start();

和MediaPlayerUtility类:

public class MediaPlayerUtility {


    public static long getTime(MediaPlayer mediaPlayer) {


        long totalDuration = mediaPlayer.getDuration(); // to get total duration in milliseconds

        long currentDuration = mediaPlayer.getCurrentPosition(); // to Gets the current playback position in milliseconds

        return currentDuration;

    }


}