4

我想创建一个 seekBar 来跟踪媒体播放器的进度,但效果不佳,正在播放音乐,但 seekbar 保持空闲状态。有什么我遗漏的吗?

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    seekBar = (SeekBar) findViewById(R.id.seekBar1);
    seekBar.setOnSeekBarChangeListener(this);

}

public void onClick(View v){
    if(v == stopButton){
        mediaPlayer.pause();
    }else if(v == startButton){
        mediaPlayer.start();
        run();
    }else if(v == quitButton ){
        mediaPlayer.stop();
        mediaPlayer.release();
    }
}

public void run() {
    int currentPosition= 0;
    int total = mediaPlayer.getDuration();
    while (mediaPlayer.isPlaying()) {
        currentPosition= mediaPlayer.getCurrentPosition();           
        seekBar.setProgress(currentPosition);
    }
}
4

1 回答 1

5

Android Building Audio Player Tutorial中,请参阅更新 SeekBar 进度和计时器部分

/**
     * Update timer on seekbar
     * */
    public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);
    }   

    /**
     * Background Runnable thread
     * */
    private Runnable mUpdateTimeTask = new Runnable() {
           public void run() {
               long totalDuration = mp.getDuration();
               long currentDuration = mp.getCurrentPosition();

               // Displaying Total Duration time
               songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
               // Displaying time completed playing
               songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

               // Updating progress bar
               int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
               //Log.d("Progress", ""+progress);
               songProgressBar.setProgress(progress);

               // Running this thread after 100 milliseconds
               mHandler.postDelayed(this, 100);
           }
        };

    /**
     *
     * */
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

    }

    /**
     * When user starts moving the progress handler
     * */
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        // remove message Handler from updating progress bar
        mHandler.removeCallbacks(mUpdateTimeTask);
    }

    /**
     * When user stops moving the progress hanlder
     * */
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mHandler.removeCallbacks(mUpdateTimeTask);
        int totalDuration = mp.getDuration();
        int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

        // forward or backward to certain seconds
        mp.seekTo(currentPosition);

        // update timer progress again
        updateProgressBar();
    }
于 2013-05-09T03:58:30.023 回答