Mediaplayer progress update to seekbar not smooth?

前端 未结 6 2026
情话喂你
情话喂你 2021-02-01 07:00

I am working on an app with recorder and player. I am using mediaplayer to play the recorded .wav file and meantime I want to update to a seekbar. Everything is working fine But

6条回答
  •  梦谈多话
    2021-02-01 07:37

    Here is how i handle the seekbar;

            mediaPlayer.setOnPreparedListener(new OnPreparedListener(){
    
            @Override
            public void onPrepared(MediaPlayer mp) {
                mediaPlayer.start();
                new SeekBarHandler().execute();
        });
    

    Now i have an Async Task called SeekBarHandler that handles the seekbar like this:

        public class SeekBarHandler extends AsyncTask {
    
    @Override
    protected void onPostExecute(Void result) {
        Log.d("##########Seek Bar Handler ################","###################Destroyed##################");
        super.onPostExecute(result);
    }
    
    @Override
    protected void onProgressUpdate(Void... values) {
        seekBar.setProgress(mediaPlayer.getCurrentPosition());
        super.onProgressUpdate(values);
    }
    
    @Override
    protected Void doInBackground(Void... arg0) {
        while(mediaPlayer.isPlaying()&&isViewOn==true) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        onProgressUpdate();
        }
        return null;
    }
    
        }
    

    Now in my onPause, i terminate the AsyncTask as it doesnt make sense to keep the thread going when the user is not able to see the seekbar

        protected void onPause() {
        isViewOn=false;
        super.onPause();
        }
    

    And on onResume i start the AsyncTaskAgain like this

        protected void onResume() {
        isViewOn=true;
        new SeekBarHandler().execute();
        super.onResume();
        }
    

    As you can see i use a boolean flag isViewOn to check whether the view is on or not to handle the seekbar.

提交回复
热议问题