Android 播放音频文件时平稳增加进度条

Android 播放音频文件时平稳增加进度条,android,android-progressbar,Android,Android Progressbar,我在我的应用程序中播放不同大小的音频文件,当音频播放时,进度条应进展顺利,但进度条采取随机大小的步骤 我正在使用以下代码: mp = new MediaPlayer(); mp.setDataSource("audio file path"); mp.prepare(); mp.start(); pb.setMax(mp.getDuration()); new AsyncTask<Void, Integer, Void>() {

我在我的应用程序中播放不同大小的音频文件,当音频播放时,进度条应进展顺利,但进度条采取随机大小的步骤

我正在使用以下代码:

 mp = new MediaPlayer(); 
 mp.setDataSource("audio file path");
 mp.prepare();
 mp.start();
 pb.setMax(mp.getDuration());
            new AsyncTask<Void, Integer, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    while(mp.isPlaying())
                    {
                     publishProgress(mp.getCurrentPosition);
                    }
                    return null;
                }
                 protected void onProgressUpdate(Integer... progress) {
                     pb.setProgress(progress[0]);
                 }
                @Override
                protected void onPostExecute(Void result) {
                    super.onPostExecute(result);
                    mp.stop();
                    mp.release();
                }
            }.execute();
mp=newmediaplayer();
mp.setDataSource(“音频文件路径”);
mp.prepare();
mp.start();
pb.setMax(mp.getDuration());
新建异步任务(){
@凌驾
受保护的Void doInBackground(Void…参数){
while(mp.isPlaying())
{
出版进度(mp.getCurrentPosition);
}
返回null;
}
受保护的void onProgressUpdate(整数…进度){
pb.setProgress(progress[0]);
}
@凌驾
受保护的void onPostExecute(void结果){
super.onPostExecute(结果);
mp.stop();
mp.release();
}
}.execute();

有没有办法平稳地增加progressbar?

请检查此步骤

步骤1: 使用MediaPlayer.getDuration()获取音频持续时间

步骤2: 将ProgressBar进度最大值设置为步骤1中的值

步骤3:

使用处理程序播放媒体时,定期从
MediaPlayer.getCurrentPosition()
更新进度条

所以代码是这样的

MediaPlayer mMediaPlayer = new MediaPlayer();
    final SeekBar mSeelBar = new SeekBar(this);
    final int duration = mMediaPlayer.getDuration();
    final int amountToUpdate = duration / 100;
    Timer mTimer = new Timer();
    mTimer.schedule(new TimerTask() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (!(amountToUpdate * mSeelBar.getProgress() >= duration)) {
                        int p = mSeelBar.getProgress();
                        p += 1;
                        mSeelBar.setProgress(p);
                    }
                }
            });
        };
    }, amountToUpdate);

我遵循了代码的链接

您可以使用以下逻辑使其更平滑

  • 将进度条的当前值和最新进度值存储为成员

  • 调用
    onProgressUpdate
    方法时更新后者

  • 在计时器中,将此逻辑定期执行

    if (currentValue < latestProgress) {
        currentValue++;
        pb.setProgress(currentValue);
    }
    
    if(当前值
    请注意,它将缓慢地向其目标值前进


  • 希望这有帮助。

    将进度条的最大大小设置为一个较高的范围。。。如果你将进度条设置为1到最大100之间的增量,那么不要使用100作为最大值,而是使用1000。这是我的建议。因为我发现你的代码工作正常

    这是我创建的mediaplayer,请查看

      public TextView songName,startTimeField,endTimeField;
       private MediaPlayer mediaPlayer;
       private double startTime = 0;
       private double finalTime = 0;
       private Handler myHandler = new Handler();;
       private int forwardTime = 5000; 
       private int backwardTime = 5000;
       private SeekBar seekbar;
       private ImageButton playButton,pauseButton;
       public static int oneTimeOnly = 0;
       @Override
       protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          songName = (TextView)findViewById(R.id.textView4);
          startTimeField =(TextView)findViewById(R.id.textView1);
          endTimeField =(TextView)findViewById(R.id.textView2);
          seekbar = (SeekBar)findViewById(R.id.seekBar1);
          playButton = (ImageButton)findViewById(R.id.imageButton1);
          pauseButton = (ImageButton)findViewById(R.id.imageButton2);
          songName.setText("song.mp3");
          mediaPlayer = MediaPlayer.create(this, R.raw.song);
          seekbar.setClickable(false);
          pauseButton.setEnabled(false);
    
       }
    
       @TargetApi(Build.VERSION_CODES.GINGERBREAD) public void play(View view){
       Toast.makeText(getApplicationContext(), "Playing sound", 
       Toast.LENGTH_SHORT).show();
          mediaPlayer.start();
          finalTime = mediaPlayer.getDuration();
          startTime = mediaPlayer.getCurrentPosition();
          if(oneTimeOnly == 0){
             seekbar.setMax((int) finalTime);
             oneTimeOnly = 1;
          } 
    
          endTimeField.setText(String.format("%d min, %d sec", 
             TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
             TimeUnit.MILLISECONDS.toSeconds((long) finalTime) - 
             TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
             toMinutes((long) finalTime)))
          );
          startTimeField.setText(String.format("%d min, %d sec", 
             TimeUnit.MILLISECONDS.toMinutes((long) startTime),
             TimeUnit.MILLISECONDS.toSeconds((long) startTime) - 
             TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
             toMinutes((long) startTime)))
          );
          seekbar.setProgress((int)startTime);
          myHandler.postDelayed(UpdateSongTime,100);
          pauseButton.setEnabled(true);
          playButton.setEnabled(false);
       }
    
       private Runnable UpdateSongTime = new Runnable() {
          @TargetApi(Build.VERSION_CODES.GINGERBREAD) public void run() {
             startTime = mediaPlayer.getCurrentPosition();
             startTimeField.setText(String.format("%d min, %d sec", 
                TimeUnit.MILLISECONDS.toMinutes((long) startTime),
                TimeUnit.MILLISECONDS.toSeconds((long) startTime) - 
                TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
                toMinutes((long) startTime)))
             );
             seekbar.setProgress((int)startTime);
             myHandler.postDelayed(this, 100);
          }
       };
       public void pause(View view){
          Toast.makeText(getApplicationContext(), "Pausing sound", 
          Toast.LENGTH_SHORT).show();
    
          mediaPlayer.pause();
          pauseButton.setEnabled(false);
          playButton.setEnabled(true);
       }    
       public void forward(View view){
          int temp = (int)startTime;
          if((temp+forwardTime)<=finalTime){
             startTime = startTime + forwardTime;
             mediaPlayer.seekTo((int) startTime);
          }
          else{
             Toast.makeText(getApplicationContext(), 
             "Cannot jump forward 5 seconds", 
             Toast.LENGTH_SHORT).show();
          }
    
       }
       public void rewind(View view){
          int temp = (int)startTime;
          if((temp-backwardTime)>0){
             startTime = startTime - backwardTime;
             mediaPlayer.seekTo((int) startTime);
          }
          else{
             Toast.makeText(getApplicationContext(), 
             "Cannot jump backward 5 seconds",
             Toast.LENGTH_SHORT).show();
          }
    
       }
    
    public TextView歌曲名、startTimeField、endTimeField;
    私人媒体播放器;
    专用双起始时间=0;
    私人双最终时间=0;
    私有处理程序myHandler=新处理程序();;
    专用int forwardTime=5000;
    专用int backwardTime=5000;
    私人SeekBar SeekBar;
    专用图像按钮播放按钮、暂停按钮;
    公共静态int-oneTimeOnly=0;
    @凌驾
    创建时受保护的void(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    songName=(TextView)findViewById(R.id.textView4);
    startTimeField=(TextView)findViewById(R.id.textView1);
    endTimeField=(TextView)findViewById(R.id.textView2);
    seekbar=(seekbar)findViewById(R.id.seekBar1);
    playButton=(ImageButton)findViewById(R.id.imageButton1);
    pauseButton=(ImageButton)findViewById(R.id.imageButton2);
    songName.setText(“song.mp3”);
    mediaPlayer=mediaPlayer.create(这个,R.raw.song);
    seekbar.setClickable(假);
    pauseButton.setEnabled(false);
    }
    @TargetApi(构建版本代码姜饼)公共无效播放(查看){
    Toast.makeText(getApplicationContext(),“播放声音”,
    吐司。长度(短)。show();
    mediaPlayer.start();
    finalTime=mediaPlayer.getDuration();
    startTime=mediaPlayer.getCurrentPosition();
    if(oneTimeOnly==0){
    seekbar.setMax((int)finalTime);
    一次性=1;
    } 
    endTimeField.setText(String.format(“%d分钟,%d秒”),
    时间单位。毫秒。toMinutes((长)finalTime),
    时间单位。毫秒。到秒((长)最终时间)——
    TimeUnit.MINUTES.toSeconds(TimeUnit.millides。
    toMinutes((长)finalTime)))
    );
    startTimeField.setText(String.format(“%d分钟,%d秒”),
    时间单位。毫秒。t分钟((长)开始时间),
    时间单位毫秒到秒((长)开始时间)-
    TimeUnit.MINUTES.toSeconds(TimeUnit.millides。
    t分钟((长)开始时间)
    );
    seekbar.setProgress((int)startTime);
    postDelayed(UpdateSongTime,100);
    pauseButton.setEnabled(true);
    playButton.setEnabled(假);
    }
    private Runnable UpdateSongTime=new Runnable(){
    @TargetApi(Build.VERSION\u CODES.GINGERBREAD)公共无效运行(){
    startTime=mediaPlayer.getCurrentPosition();
    startTimeField.setText(String.format(“%d分钟,%d秒”),
    时间单位。毫秒。t分钟((长)开始时间),
    时间单位毫秒到秒((长)开始时间)-
    TimeUnit.MINUTES.toSeconds(TimeUnit.millides。
    t分钟((长)开始时间)
    );
    seekbar.setProgress((int)startTime);
    myHandler.postDelayed(这个,100);
    }
    };
    公共无效暂停(视图){
    Toast.makeText(getApplicationContext(),“暂停声音”,
    吐司。长度(短)。show();
    mediaPlayer.pause();
    pauseButton.setEnabled(false);
    playButton.setEnabled(真);
    }    
    公共无效前进(视图){
    int temp=(int)开始时间;
    如果((临时+转发时间)0){
    startTime=startTime-后退时间;
    mediaPlayer.seekTo((int)startTime);
    }
    否则{
    Toast.makeText(getApplicationContext(),
    “不能向后跳5秒”,
    吐司。长度(短)。show();
    }
    }
    
    尽管建议在播放时使用Handler跟踪音频的当前位置是唯一正确的方法。但是,简而言之,
    MediaPlayer.getCurrentPosition()
    不是超精确的